Redis study notes (3) java operation Redis


(1) Preparation before
use Using Java to operate Redis requires jedis, and this article uses jedis-2.1.0.jar

(2) Code instance

   Strange errors will occur when the same Jedis instance is used in different threads. But creating too many implementations is not good either because it means a lot of sokcet connections are made, which can also cause weird bugs to happen. A single Jedis instance is not thread safe. To avoid these problems, you can use JedisPool, which is a thread-safe network connection pool. You can use JedisPool to create some reliable Jedis instances, and you can get Jedis instances from the pool. This way can solve those problems and achieve efficient performance


jeditPool utility class

package com.testedis;



import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Weird bugs occur when using the same Jedis instance in different threads. But creating too many implementations is not good either because it means many sokcet connections are made,
 * can also cause weird errors to occur. A single Jedis instance is not thread safe. To avoid these problems, you can use JedisPool,
 * JedisPool is a thread-safe network connection pool. You can use JedisPool to create some reliable Jedis instances, and you can get Jedis instances from the pool.
 * This way can solve those problems and will achieve efficient performance
 */  
public final class RedisUtil {
    
    //Redis server IP
    private static String ADDR = "127.0.0.1";
    
    //Redis port number
    private static int PORT = 6379;
    
    //Access password
    private static String AUTH = "test1104";
    
    //The maximum number of available connection instances, the default value is 8;
    //If the value is -1, it means there is no limit; if the pool has allocated maxActive jedis instances, the state of the pool is exhausted at this time.
    private static int MAX_ACTIVE = 1024;
    
    //Control the maximum number of jedis instances in idle (idle) status in a pool, the default value is also 8.
    private static int MAX_IDLE = 200;
    
    //The maximum time to wait for an available connection, in milliseconds, the default value is -1, which means never timeout. If the waiting time is exceeded, JedisConnectionException is thrown directly;
    private static int MAX_WAIT = 10000;
    
    private static int TIMEOUT = 10000;
    
    //When borrowing a jedis instance, whether to perform the validate operation in advance; if it is true, the obtained jedis instance is available;
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool = null;
    
    /**
     * Initialize the Redis connection pool
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxActive(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWait(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
    
    /**
     * Get the Jedis instance
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace ();
            return null;
        }
    }
    
    /**
     * Release jedis resources
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
}





Redis operation example

package com.testedis;



import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;



import redis.clients.jedis.Jedis;

public class TestRedis {
    private Jedis jedis;
    
    
    public void init() {
    	jedis= RedisUtil.getJedis();
    }
    
    /**
     * redis store string
     */
    
    public void testString() {
    	jedis.del("name");
        //-----adding data----------  
        jedis.set("name","xinxin");//Put value-->xinxin into key-->name  
        System.out.println(jedis.get("name"));//Execution result: xinxin  
        
        jedis.append("name", " is my lover"); //拼接
        System.out.println(jedis.get("name"));
        
        jedis.del("name"); //Delete a key
        System.out.println(jedis.get("name"));
        // set multiple key-value pairs
        jedis.mset("name","liuling","age","23","qq","476777XXX");
        jedis.incr("age"); //Add 1 operation
        System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
        
    }
    
    /**
     * redis operation Map
     */
   
    public void testMap() {
    	jedis.del("userMap");
        //-----adding data----------  
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "xinxin");
        map.put("age", "22");
        map.put("qq", "123456");
        jedis.hmset("userMap",map);
        // Take out the name, age, qq in userMap and execute the result: [xinxin, 22, 123456]--> Note that the result is a generic List  
        //The first parameter is the key of the map object stored in redis, followed by the key of the object put into the map, and the following keys can be followed by multiple, variable parameters  
        List<String> rsmap = jedis.hmget("userMap", "name", "age", "qq");
        System.out.println("Take out the name, age, qq in userMap: "+rsmap);  
  
        // delete a key in the map  
        jedis.hdel("userMap","age");
        System.out.println("Deleted, so it returns null:"+jedis.hmget("userMap", "age")); //Because it is deleted, it returns null  
        System.out.println(jedis.hlen("userMap")); //return the number of values ​​stored in the key whose key is user 2
        System.out.println(jedis.exists("userMap"));//Whether there is a record whose key is userMap returns true  
        System.out.println(jedis.hkeys("userMap"));//Return all keys in the map object  
        System.out.println(jedis.hvals("userMap"));//Return all values ​​in the map object
  
        Iterator<String> iter=jedis.hkeys("userMap").iterator();  
        while (iter.hasNext()){  
            String key = iter.next();  
            System.out.println(key+":"+jedis.hmget("userMap",key));  
        }  
    }
    
    /**
     * jedis operation List
     */  
     
    public void testList(){  
        // Before starting, remove all content  
        jedis.del("java framework");  
        System.out.println(jedis.lrange("java framework",0,-1));  
        //First store three pieces of data in the key java framework  
        jedis.lpush("java framework","spring");  
        jedis.lpush("java framework","struts");  
        jedis.lpush("java framework","hibernate");  
        jedis.lpush("java framework","ibatis");
        // Then take out all the data jedis.lrange is taken out by range,  
        // The first is the key, the second is the start position, the third is the end position, jedis.llen gets the length -1 means get all  
        System.out.println(jedis.lrange("java framework",0,-1));  
        //Popping the stack, starting from the last added data, the principle of first-in, last-out.
         jedis.lpop("java framework");
         System.out.println(jedis.lrange("java framework",0,-1));
         //Delete data outside the interval, index=0 means the first data
         jedis.ltrim("java framework", 0, 1);
         System.out.println(jedis.lrange("java framework",0,-1));
         //Get the value of the specified subscript
         System.out.println(jedis.lindex("java framework",0));
         //Set the value of the specified subscript
         jedis.lset("java framework", 0, "hibernate2.5");
         System.out.println(jedis.lrange("java framework",0,-1));
    }  
    
    /**
     * jedis operation Set
     */  
      
    public void testSet(){  
    	jedis.del("user1");  
        //Add to  
        jedis.sadd("user1","liuling");  
        jedis.sadd("user1","xinxin");  
        jedis.sadd("user1","ling");  
        jedis.sadd("user1","zhangxinxin");
        jedis.sadd("user1","who");  
        // remove who  
        jedis.srem("user1","who");  
        System.out.println(jedis.smembers("user1"));//Get all added values  
        System.out.println(jedis.sismember("user1", "who"));//Determine whether who is an element of the user1 set  
        System.out.println(jedis.srandmember("user1")); //Get the elements in the set randomly
        System.out.println(jedis.scard("user1"));//Returns the number of elements in the collection  
        
        jedis.del("user2");
        //add user2
        jedis.sadd("user2","liuling");
        jedis.sadd("user2","zhangxinxin");
        jedis.sadd("user2","liudehua");
        jedis.sadd("user2","jiangxin");
        System.out.println("View all elements in the user1 collection:"+jedis.smembers("user1"));
        System.out.println("View all elements in user2 collection:"+jedis.smembers("user2"));
        //set operation
        System.out.println("Intersection of user1 and user2:"+jedis.sinter("user1", "user2"));//Elements shared by user1 and user2
        System.out.println("user1 and user2 union: "+jedis.sunion("user1", "user2"));// Merge the two sets, the set elements are not repeated after the merge
        System.out.println("The difference between user1 and user2: "+jedis.sdiff("user1", "user2"));//The difference: there are elements in user1 but not in user2
    }   
  
    /****
     * ZSet is an ordered set
     */
    public void testZSet ()
    {
    	jedis.del("user3");  
    	jedis.zadd("user3", 30, "Huang Xiaoming is an actor");
    	jedis.zadd("user3", 55, "Feng Xiaogang is a director");
    	jedis.zadd("user3", 33, "Zhang Jie is a singer");
    	jedis.zadd("user3", 31, "Li Xiaoming is a courier");
    	jedis.zadd("user3", 32, "Yao Bin is a programmer");
    	System.out.println("所有元素:"+jedis.zrange("user3", 0, -1));
    	System.out.println("key=user3's set of score column values ​​in the middle of 30-32 elements:"+jedis.zcount("user3", 30, 32));//The value of the statistical score column is at the minimum number of elements between and max
    	System.out.println("key=user3's set of score column values ​​in the middle of 30-32 elements:"+jedis.zrangeByScore("user3", 30, 32));
    	System.out.println(jedis.zscore("user3", "Zhang Jie is a singer"));
    }
     
    public void test() throws InterruptedException {  
        //jedis sort  
        //Note that rpush and lpush here are List operations. is a doubly linked list (but from a performance point of view)  
        jedis.del("a");//Clear data first, then add data for testing  
        jedis.rpush("a", "1");  
        jedis.lpush("a","6");  
        jedis.lpush("a","3");  
        jedis.lpush("a","9");  
        
        System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1]  
        System.out.println(jedis.sort("a")); //[1, 3, 6, 9] //Enter the sorted result  
        System.out.println(jedis.lrange("a",0,-1));  
    }  
    
    
    public void returnResource()
    {
    	RedisUtil.returnResource(jedis);
    }
    
    
    public static void main(String[] args)
    {
    	TestRedis test = new TestRedis ();
    	//Initialize Redis
    	test.init();
    	try {
			test.testString();
    		test.testList();
    		test.test();
    		test.testMap ();
    		test.testSet();
    		test.testZSet ();
    		
    		// release resources
    		test.returnResource();
    		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		
    }
}



In the previous chapter, we introduced a Redis interface management tool, Redis Desktop Manage. When you start it, you can see some key-value lists. We can easily add, delete, and modify it.



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326876471&siteId=291194637