Got it

Redis:Basic Redis Operations

Latest reply: Jul 19, 2018 03:30:58 2078 5 1 0 0

1.1.1 Case 1: Basic Redis Operations

1.1.1.1 Scenarios

Scenario Description

The service operation object of the Redis is key. Operations covered in example codes include access operations for keys of the String, List, Hash, Set, and Sorted Set types.

Example codes are described in the following sequence:

l   Redis cluster initialization

l   String type access

l   List type access

l   Hash type access

l   Set type access

l   Sorted Set type access

1.1.1.2 Development Idea

None

1.1.1.3 Example Code Description

1.1.1.3.1 Redis Cluster Initialization

Function

Create JedisCluster instances by specifying the IP addresses and port IDs of one or more instances in a cluster.

Example Code

The following code snippet belongs to the RedisTest method in the RedisTest class of the com.huawei.redis.demo package.

    public RedisTest() {

        Set<HostAndPort> hosts = new HashSet<HostAndPort>();

        hosts.add(new HostAndPort(Const.IP_1, Const.PORT_1));

        hosts.add(new HostAndPort(Const.IP_2, Const.PORT_2));

        // add more host...

        // socket timeout(connect, read), unit: ms

        int timeout = 5000;

        client = new JedisCluster(hosts, timeout);

    }

note

l  On FusionInsight Manager, users can view the Redis instances included in the Redis clusters.

l  In the Redis cluster, the port ID corresponding to role Redis_1 is 22400, and the port ID corresponding to role Redis_2 is 22401. The others follow the same rule.

l  Set the values, such as Const.IP_1, Const.IP_2, Const.PORT_1, and Const.PORT_2 in the Const class of the com.huawei.redis package, to the IP addresses and port IDs in the actual environment.

1.1.1.3.2 String Type Access

Function

Implement setting and obtaining data of simple String type in the Redis, through the methods such as set and get in the JedisCluster instance.

Example Code

The following code snippet belongs to the testString method in the RedisTest class of the com.huawei.redis.demo package.

    public void testString() {

        String key = "sid-user01";

        // Save user's session ID, and set expire time

        client.setex(key, 5, "A0BC9869FBC92933255A37A1D21167B2");

        String sessionId = client.get(key);

        LOGGER.info("User " + key + ", session id: " + sessionId);

        try {

            Thread.sleep(10000);

        } catch (InterruptedException e) {

            LOGGER.warn("InterruptedException");

        }

        sessionId = client.get(key);

        LOGGER.info("User " + key + ", session id: " + sessionId);

        key = "message";

        client.set(key, "hello");

        String value = client.get(key);

        LOGGER.info("Value: " + value);

        client.append(key, " world");

        value = client.get(key);

        LOGGER.info("After append, value: " + value);

        client.del(key);

    }

Precautions

All types of key in the Redis are case-sensitive.

1.1.1.3.3 List Type Access

Function

Implement setting and obtaining data of List type in the Redis, through the methods such as rpush and lpop in the JedisCluster instance.

Example Code

The following code snippet belongs to the testList method in the RedisTest class of the com.huawei.redis.demo package.

    public void testList() {

        String key = "messages";

        // Right push

        client.rpush(key, "Hello how are you?");

        client.rpush(key, "Fine thanks. I'm having fun with redis.");

        client.rpush(key, "I should look into this NOSQL thing ASAP");

        // Fetch all data

        List<String> messages = client.lrange(key, 0, -1);

        LOGGER.info("All messages: " + messages);

        long len = client.llen(key);

        LOGGER.info("Message count: " + len);

        // Fetch the first element and delete it from list

        String message = client.lpop(key);

        LOGGER.info("First message: " + message);

        len = client.llen(key);

        LOGGER.info("After one pop, message count: " + len);

        client.del(key);

    }

1.1.1.3.4 Hash Type Access

Function

Implement setting and obtaining data of Hash type in the Redis, through the methods such as hset, hget, hmset and hgetall in the JedisCluster instance.

Example Code

The following code snippet belongs to the testHash method in the RedisTest class of the com.huawei.redis.demo package.

    public void testHash() {

        String key = "userinfo-001";

        // like Map.put()

        client.hset(key, "id", "J001");

        client.hset(key, "name", "John");

        client.hset(key, "gender", "male");

        client.hset(key, "age", "35");

        client.hset(key, "salary", "1000000");

        // like Map.get()

        String id = client.hget(key, "id");

        String name = client.hget(key, "name");

        LOGGER.info("User " + id + "'s name is " + name);

        Map<String, String> user = client.hgetAll(key);

        LOGGER.info(user);

        client.del(key);

        key = "userinfo-002";

        Map<String, String> user2 = new HashMap<String, String>();

        user2.put("id", "L002");

        user2.put("name", "Lucy");

        user2.put("gender", "female");

        user2.put("age", "25");

        user2.put("salary", "200000");

        client.hmset(key, user2);

        client.hincrBy(key, "salary", 50000);

        id = client.hget(key, "id");

        String salary = client.hget(key, "salary");

        LOGGER.info("User " + id + "'s salary is " + salary);

        // like Map.keySet()

        Set<String> keys = client.hkeys(key);

        LOGGER.info("all fields: " + keys);

        // like Map.values()

        List<String> values = client.hvals(key);

        LOGGER.info("all values: " + values);

        // Fetch some fields

        values = client.hmget(key, "id", "name");

        LOGGER.info("partial field values: " + values);

        // like Map.containsKey();

        boolean exist = client.hexists(key, "gender");

        LOGGER.info("Exist field gender? " + exist);

        // like Map.remove();

        client.hdel(key, "age");

        keys = client.hkeys(key);

        LOGGER.info("after del field age, rest fields: " + keys);

        client.del(key);

    }

1.1.1.3.5 Set Type Access

Function

Implement setting and obtaining of Set type in the Redis, through the methods such as sadd and smember in the JedisCluster instance.

Example Code

The following code snippet belongs to the testSet method in the RedisTest class of the com.huawei.redis.demo package.

    public void testSet() {

        String key = "sets";

        client.sadd(key, "HashSet");

        client.sadd(key, "SortedSet");

        client.sadd(key, "TreeSet");

        // like Set.size()

        long size = client.scard(key);

        LOGGER.info("Set size: " + size);

        client.sadd(key, "SortedSet");

        size = client.scard(key);

        LOGGER.info("Set size: " + size);

        Set<String> sets = client.smembers(key);

        LOGGER.info("Set: " + sets);

        client.srem(key, "SortedSet");

        sets = client.smembers(key);

        LOGGER.info("Set: " + sets);

        boolean ismember = client.sismember(key, "TreeSet");

        LOGGER.info("TreeSet is set's member: " + ismember);

        client.del(key);

    }

1.1.1.3.6 Sorted Set Type Access

Function

Implement setting and obtaining data of Sorted Set type in the Redis, through the methods such as zadd and zrange in the JedisCluster instance.

Example Code

The following code snippet belongs to the testSortedSet method in the RedisTest class of the com.huawei.redis.demo package.

    public void testSortedSet() {

        String key = "hackers";

        // Score: age

        client.zadd(key, 1940, "Alan Kay");

        client.zadd(key, 1953, "Richard Stallman");

        client.zadd(key, 1965, "Yukihiro Matsumoto");

        client.zadd(key, 1916, "Claude Shannon");

        client.zadd(key, 1969, "Linus Torvalds");

        client.zadd(key, 1912, "Alan Turing");

        // sort by score, ascending order

        Set<String> setValues = client.zrange(key, 0, -1);

        LOGGER.info("All hackers: " + setValues);

        long size = client.zcard(key);

        LOGGER.info("Size: " + size);

        Double score = client.zscore(key, "Linus Torvalds");

        LOGGER.info("Score: " + score);

        long count = client.zcount(key, 1960, 1969);

        LOGGER.info("Count: " + count);

        // sort by score, descending order

        Set<String> setValues2 = client.zrevrange(key, 0, -1);

        LOGGER.info("All hackers 2: " + setValues2);

        client.zrem(key, "Linus Torvalds");

        setValues = client.zrange(key, 0, -1);

        LOGGER.info("All hackers: " + setValues);

        client.del(key);

    }

1.1.1.4 Obtaining Example Codes

Using the FusionInsight Client

Decompress the FusionInsight client installation package and obtain the redis.client.demo file, which is saved in the redis sub-folder of the FusionInsight_Services_ClientConfig folder.

Maven Project Mode

Download the code from the Huawei DevCloud website to the local computer. Huawei DevCloud URL: https://codehub-cn-south-1.devcloud.huaweicloud.com/codehub/7076065/home

Security mode:components/redis/redis-examples-maven

1.1.1.5 Application Commissioning

1.1.1.5.1 Commissioning an Application in Windows

Compiling and Running an Application

Scenario

After the code development is complete, you can run the application in the Windows development environment.

Procedure

In the development environment (such as Eclipse), right-click RedisTest.java, and choose Run as > Java Application to run the application project.

Viewing Commissioning Results

Scenario

After a Redis application is run, you can check the running result through one of the following methods:

l   Viewing the Eclipse running result

l   Logging in to the Redis Shell client to view the command output

Procedure

l   Viewing the Eclipse running result

2016-04-19 13:25,929 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:53) - User sid-user01, session id: A0BC9869FBC92933255A37A1D21167B2 
2016-04-19 13:25,932 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:61) - User sid-user01, session id: null 
2016-04-19 13:25,986 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:67) - Value: hello 
2016-04-19 13:25,988 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:71) - After append, value: hello world 
2016-04-19 13:25,999 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:86) - All messages: [Hello how are you?, Fine thanks. I'm having fun with redis., I should look into this NOSQL thing ASAP] 
2016-04-19 13:25,001 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:89) - Message count: 3 
2016-04-19 13:25,003 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:93) - First message: Hello how are you? 
2016-04-19 13:25,005 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:95) - After one pop, message count: 2 
2016-04-19 13:25,036 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:113) - User J001's name is John 
2016-04-19 13:25,038 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:116) - {gender=male, name=John, id=J001, salary=1000000, age=35} 
2016-04-19 13:25,082 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:130) - User L002's salary is 250000 
2016-04-19 13:25,083 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:134) - all fields: [name, id, gender, salary, age] 
2016-04-19 13:25,083 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:137) - all values: [L002, female, Lucy, 25, 250000] 
2016-04-19 13:25,084 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:141) - partial field values: [L002, Lucy] 
2016-04-19 13:25,085 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:145) - Exist field gender? true 
2016-04-19 13:25,086 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:150) - after del field age, rest fields: [name, id, gender, salary] 
2016-04-19 13:25,090 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:164) - Set size: 3 
2016-04-19 13:25,091 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:168) - Set size: 3 
2016-04-19 13:25,092 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:171) - Set: [TreeSet, SortedSet, HashSet] 
2016-04-19 13:25,093 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:175) - Set: [TreeSet, HashSet] 
2016-04-19 13:25,094 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:178) - TreeSet is set's member: true 
2016-04-19 13:25,098 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:196) - All hackers: [Alan Turing, Claude Shannon, Alan Kay, Richard Stallman, Yukihiro Matsumoto, Linus Torvalds] 
2016-04-19 13:25,099 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:199) - Size: 6 
2016-04-19 13:25,100 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:202) - Score: 1969.0 
2016-04-19 13:25,101 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:205) - Count: 2 
2016-04-19 13:25,103 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:209) - All hackers 2: [Linus Torvalds, Yukihiro Matsumoto, Richard Stallman, Alan Kay, Claude Shannon, Alan Turing] 
2016-04-19 13:25,106 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:213) - All hackers: [Alan Turing, Claude Shannon, Alan Kay, Richard Stallman, Yukihiro Matsumoto] 
2016-04-19 13:25,109 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:224) - TTL: 5 
2016-04-19 13:25,110 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:228) - KEY type: string 
2016-04-19 13:25,112 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:237) - List: [1, 4, 6, 3, 8] 
2016-04-19 13:25,113 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:240) - Sort list: [1, 3, 4, 6, 8] 
2016-04-19 13:25,448 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:270) - Result: [www.google.cn, www.baidu.com, www.sina.com]

l   Logging in to the Redis Shell client to view the command output:

After the example code is executed, keys are deleted. Therefore, you cannot directly use the shell command to view the application running result after the example project is executed. The following uses example code of String Type Access to explain how to use the shell command to view the application running result:

note

Prerequisites:

l  The Redis client has been installed on the Linux.

l  Redis user security authentication has been performed on the client.

1.         Comment out client.del(key); in the last line of the TestString() method.

//client.del(key);

2.         Perform operations as instructed in Commissioning an Application in Windows.

3.         Run the following command on the Linux-based Redis client:

./redis-cli -c -p 22400 --realm hadoop.com get message

The value hello world set in the Java API is displayed:

[root@192-168-33-94 bin]#./redis-cli -c -p 22400 --realm hadoop.com get message 
"hello world" 

1.1.1.5.2 Commissioning an Application in Linux

Compiling and Running an Application

Scenario

In a Linux environment, you can upload the JAR file to the Linux and then run an application after the code development is complete.

Prerequisites

JDK has been installed.

Procedure

                               Step 1      Export a JAR file.

1.         Right-click the example project and choose Export from the shortcut menu.

2.         Select JAR file and click Next.

3.         Select the src directory, and export the JAR file to the specified location. Click Next twice.

4.         Click Finish.

                               Step 2      Prepare for the required JAR files and configuration files.

In the Linux environment, create a directory, for example, /opt/test, and create subdirectories config and lib. Upload the JAR files in the example project and the JAR files exported in Step 1 to the lib directory in Linux. Upload the conf configuration files in the src/config of the example project to the config directory in Linux.

                               Step 3      Go to /opt/test and run the following commands to run the JAR files:

java -cp .:lib/* com.huawei.redis.demo.RedisTest

----End

Viewing Commissioning Results

Scenario

After a Redis application is run, you can check the running result through one of the following methods:

l   Viewing the Linux running result

l   Logging in to the Redis Shell client to view the command output

Procedure

l   Viewing the Linux running result

The following success information will be displayed:

2016-04-19 13:25,929 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:53) - User sid-user01, session id: A0BC9869FBC92933255A37A1D21167B2 
2016-04-19 13:25,932 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:61) - User sid-user01, session id: null 
2016-04-19 13:25,986 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:67) - Value: hello 
2016-04-19 13:25,988 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:71) - After append, value: hello world 
2016-04-19 13:25,999 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:86) - All messages: [Hello how are you?, Fine thanks. I'm having fun with redis., I should look into this NOSQL thing ASAP] 
2016-04-19 13:25,001 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:89) - Message count: 3 
2016-04-19 13:25,003 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:93) - First message: Hello how are you? 
2016-04-19 13:25,005 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:95) - After one pop, message count: 2 
2016-04-19 13:25,036 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:113) - User J001's name is John 
2016-04-19 13:25,038 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:116) - {gender=male, name=John, id=J001, salary=1000000, age=35} 
2016-04-19 13:25,082 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:130) - User L002's salary is 250000 
2016-04-19 13:25,083 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:134) - all fields: [name, id, gender, salary, age] 
2016-04-19 13:25,083 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:137) - all values: [L002, female, Lucy, 25, 250000] 
2016-04-19 13:25,084 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:141) - partial field values: [L002, Lucy] 
2016-04-19 13:25,085 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:145) - Exist field gender? true 
2016-04-19 13:25,086 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:150) - after del field age, rest fields: [name, id, gender, salary] 
2016-04-19 13:25,090 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:164) - Set size: 3 
2016-04-19 13:25,091 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:168) - Set size: 3 
2016-04-19 13:25,092 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:171) - Set: [TreeSet, SortedSet, HashSet] 
2016-04-19 13:25,093 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:175) - Set: [TreeSet, HashSet] 
2016-04-19 13:25,094 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:178) - TreeSet is set's member: true 
2016-04-19 13:25,098 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:196) - All hackers: [Alan Turing, Claude Shannon, Alan Kay, Richard Stallman, Yukihiro Matsumoto, Linus Torvalds] 
2016-04-19 13:25,099 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:199) - Size: 6 
2016-04-19 13:25,100 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:202) - Score: 1969.0 
2016-04-19 13:25,101 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:205) - Count: 2 
2016-04-19 13:25,103 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:209) - All hackers 2: [Linus Torvalds, Yukihiro Matsumoto, Richard Stallman, Alan Kay, Claude Shannon, Alan Turing] 
2016-04-19 13:25,106 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:213) - All hackers: [Alan Turing, Claude Shannon, Alan Kay, Richard Stallman, Yukihiro Matsumoto] 
2016-04-19 13:25,109 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:224) - TTL: 5 
2016-04-19 13:25,110 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:228) - KEY type: string 
2016-04-19 13:25,112 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:237) - List: [1, 4, 6, 3, 8] 
2016-04-19 13:25,113 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:240) - Sort list: [1, 3, 4, 6, 8] 
2016-04-19 13:25,448 [main] INFO  com.huawei.redis.demo.RedisTest (RedisTest.java:270) - Result: [www.google.cn, www.baidu.com, www.sina.com]

l   Logging in to the Redis Shell client to view the command output

After the example code is executed, keys are deleted. Therefore, you cannot directly use the shell command to view the application running result after the example project is executed. The following uses example code of String Type Access to explain how to use the shell command to view the application running result:

note

Prerequisites:

l  The Redis client has been installed on the Linux.

l  Redis user security authentication has been performed on the client.

1.         Comment out client.del(key); in the last line of the TestString() method.

//client.del(key);

2.         Perform operations as instructed inCommissioning an Application in Linux.

3.         Run the following command on the Linux-based Redis client:

./redis-cli -c -p 22400 --realm hadoop.com get message

The value hello world set in the Java API is displayed:

[root@192-168-33-94 bin]#./redis-cli -c -p 22400 --realm hadoop.com get message 
"hello world" 

 


This post was last edited by chz at 2016-04-19 13:25.

This article contains more resources

You need to log in to download or view. No account? Register

x

good!:)
View more
  • x
  • convention:

thanks for sharing
View more
  • x
  • convention:

I have a basic understanding of Redis through this article. Thank you.
View more
  • x
  • convention:

welcomeRedis:Basic Redis Operations-2700481-1
View more
  • x
  • convention:

Useful, get!:)
View more
  • x
  • convention:

Comment

You need to log in to comment to the post Login | Register
Comment

Notice: To protect the legitimate rights and interests of you, the community, and third parties, do not release content that may bring legal risks to all parties, including but are not limited to the following:
  • Politically sensitive content
  • Content concerning pornography, gambling, and drug abuse
  • Content that may disclose or infringe upon others ' commercial secrets, intellectual properties, including trade marks, copyrights, and patents, and personal privacy
Do not share your account and password with others. All operations performed using your account will be regarded as your own actions and all consequences arising therefrom will be borne by you. For details, see " User Agreement."

My Followers

Login and enjoy all the member benefits

Login

Block
Are you sure to block this user?
Users on your blacklist cannot comment on your post,cannot mention you, cannot send you private messages.
Reminder
Please bind your phone number to obtain invitation bonus.