Redis Series Learning (iii) Java API access and transaction __redis

Source: Internet
Author: User
Tags redis rollback

Redis Series Learning (iii) Java API access and transactions

Introduction Two first simple example three business

first, the introduction

To access the Redis database to Java, the first officially recommended Jedis framework, which contains REDIS basic operations and command line operations. It is very convenient for us to work.
git address

MAVEN's Pom.xml reference:

<dependency>
        <groupId>redis.clients</groupId>
        <artifactid>jedis</artifactid >
        <version>2.9.0</version>
</dependency>
Second, the first simple example

Examples include the previous article to learn the command line operation of the corresponding API method, because we have learned the command line operation Redis Database method, here time to study the API, we believe it is not so difficult.

Example

Package Com.sea;
Import Java.util.HashMap;

Import Java.util.Map;
Import redis.clients.jedis.BinaryClient;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig;

    public class Redisclient {//Client connection private Jedis Jedis;

    Client Connection pool private Jedispool jedispool;
        Public redisclient () {initialpool ();
    Jedis = Jedispool.getresource (); }/** * Initialize/private void Initialpool () {//Pool basic configuration jedispoolconfig config = new Jedis
        Poolconfig ();
        Config.setmaxtotal (20);
        Config.setmaxidle (5);
        Config.setmaxwaitmillis (1000l);
        Config.settestonborrow (FALSE);
    Jedispool = new Jedispool (config, "127.0.0.1", 6379);
        public void Show () {testoperate ();
    Releasing resources jedispool.close ();
    private void Testoperate () {System.out.println ("====================== General Command Operation ==========================");    Jedis.keys ("*");/Find the Key Jedis.keys ("test*");//Find Key Jedis.del ("TT") beginning with test;//delete Jedis.exis TS ("TT"), or whether the query key exists jedis.expire ("name", 60),//Set the expiration time, the unit seconds Jedis.ttl ("name"), or view the time that the key is left out of the timeout Jedis . Type ("name");//view key data Type JEDIS.FLUSHDB ()//Clear Data Jedis.auth ("123456");/Set Connection password System.out.print
        ln ("======================string command Operation ==========================");
        Add Jedis.set ("name", "Chenyuan");
        Jedis.set ("Age", "100");

        System.out.println ("Test string Add:" + jedis.get ("name"));
        Modify Jedis.set ("name", "Chenyuan"); Jedis.append ("name", "33");//Append JEDIS.INCR ("age");/+ 1 JEDIS.DECR ("age");//minus 1 Jedis.incrby ("Age",

        6)//plus the specified value Jedis.decrby ("Age", 6);//subtract the specified value System.out.println ("Test string modification:" + jedis.get ("name")); Delete Jedis.del ("name");//single Delete Jedis.del ("name", "Age");//Multiple Delete System.out.println ("Test string deletion:" + Jedis .Get ("name"));
        System.out.println ("======================hash command Operation =========================="); Add Jedis.hset ("Testhash", "Counrty", "a");//Adding a record to the Testhash table map<string,string> data = new Ha
        Shmap<string, string> ();
        Data.put ("Sex", "man");
        Data.put ("Add", "Nibo"); Jedis.hmset ("Testhash", data); Add multiple records to the Testhash table//Modify Jedis.hset ("Testhash", "Counrty", "china1");//Direct cover
        Cover value Jedis.hset ("Testhash", "Age", "999");//Direct Overwrite value Jedis.hincrby ("Testhash", "Age", 1);//Increase specified value//find Jedis.hget ("Testhash", "Counrty");/find/Extend command jedis.hexists ("Testhash", "Counrty");//Judge Testhash table Whether the presence of key is Counrty element Jedis.hlen ("Testhash");//Table Length Jedis.hkeys ("Testhash");//Get So keys jedis.hvals ("Te Sthash ");//get so values//delete Jedis.hdel (" Testhash "," Counrty ");//delete a single record Jedis.hdel (" Testhash "," Co Unrty "," age ");//delete more than one record, ignore SYSTEM.OUT.PRintln ("======================list command Operation =========================="); Add Jedis.lpushx ("Testlist", "1,2,3,4,5,6,a,b,c,d,e,f");//Shang Insert data and ignore Jedis.lpush ("Testlist", "1,2,3,4") , 5,6,a,b,c,d,e,f ");//Shang Insert data, the table does not exist to create Jedis.linsert (" Testlist ", binaryclient.list_position. Before, "E", "99")//Inserts the Jedis.linsert ("Testlist", binaryclient.list_position) before the element value is f. After, "F", "100")//Insert 100//delete Jedis.rpop ("Testlist") after the element value is f;/popup Jedis.lrem ("Testlist", 2, " D ");/the instruction deletes the element with the value of count; If count is greater than 0, it is traversed from the beginning, if count is less than 0, and if count is equal to 0, delete all elements equal to a value in the list//modify Jedis.lset ("Testlist", 0, "AA");/modify the specified index number

 The value of the position//query Jedis.lrange ("Testlist", 0, 3);//Find a range value}}

A single Jedis instance is not thread-safe. To avoid these problems, you can use Jedispool,jedispool to be a thread-safe network connection pool. You can use Jedispool to create some reliable Jedis instances from which you can get Jedis instances. third, the business

A transaction is a continuous state that is not interrupted by other processes, either successfully together or fail together. Ensure consistency and integrity of data.
Redis transactions Ensure that the command is ordered, sequential, and that the middle is not threaded by other client commands.
All commands in the Redis transaction are serialized, executed sequentially, Redis does not provide any service to other database clients during the execution of the transaction, thus guaranteeing that all the commands in the transaction are atomized, and that the commands in the transaction are either all executed or none are executed.

Open transaction: Multi
COMMIT TRANSACTION: EXEC
rollback command: Discard (Clear all previously queued commands in one transaction, then restore normal connection status)
Add monitoring: Watch (key), monitor the change of a key, If this (or these) key is changed by another command before the transaction is executed, all commands in the transaction are canceled.
Canceling monitoring: unwatch (Key)

The method corresponding to the Java API is as follows:

        Account opening transaction, return transaction object 
        Transaction Transaction = Jedis.multi ();

        Submit Transaction
        transaction.exec ();

        Roll back
        Transaction.discard ();

        Monitor changes to key values
        transaction.watch ("name");

When the multi command is entered, the server returns OK indicating that the transaction started successfully, and then entering all the commands that need to be executed in this transaction, each time entering a command server does not execute immediately, but returns "QUEUED", which means that the command has been accepted by the server and is temporarily saved. The last time you enter the EXEC command, all the commands in this transaction are executed sequentially, and you can see that the last server returned three OK at once, and the result returned is in order one by one, which indicates that all the commands in this transaction were executed successfully.

Summary: After the account is opened, subsequent commands are added to the queue to invoke exec commit transaction directly before execution begins. Redis Guarantee 2 Importance: 1. The commands in the transaction are either fully executed or all are not executed. 2, the transaction executes the command to add sequentially executes, the middle does not disorderly preface, also will not interspersed other client commands.

Error handling mechanisms for transactions
1. Syntax error. If the command does not exist or if the argument is wrong, this is known before the EXEC command is executed, because if "QUEUED" is returned if the command queue is joined correctly, Redis will return an error if the previous version of Redis 2.6.5 ignores the wrong command and executes the other correct command. The version after 2.6.5 ignores all commands in this transaction and does not execute.
2, run the error. An error that occurs at run time, even if the error occurs (Redis received and executed without treating it as an error), and subsequent commands continue to execute.

Note: Redis rollback does not mean "rollback" in relational databases, Redis pursues a faster, more efficient algorithm that proactively ignores rollback error handling, and it wants the programmer to make sure that command execution does not go wrong

summed up. This means that the Redis supports transactions, and in the case of syntax errors, ensures that the commands are all executed or not executed, and that they are executed in addition order. In the case of a running error, Redis ignores the error command and continues with the following command.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.