Learning Redis for the first time

1 what is redis?

  • Redis is an open-source log and key value database written in ANSI C language, supporting network, memory based and persistent, and provides API s in multiple languages. In other words, redis is like a HashMap, but it does not run in the JVM, but in the form of an independent process.
  • Generally speaking, it will be used as a cache. Because it is faster than the database (mysql), so common data can be considered here, which provides performance.
  • redis official website: http://redis.io The download address of windows version is: http://redis.io/download Click in and you will jump to: https://github.com/mythz/redis-windows 

2 common commands

  • 5 data types String List Hash Set Sorted Set
  • Operation on the client side: demonstration (String)
  • If you want to query the detailed usage of each command, please go to the redis official command manual: http://www.redis.cn/commands.html

How to access and use java code

  • Download its third-party jar package: Jedis can easily access various Redis services

         

 

4. Spring's support for Redis

  1. Configure redis.properties to specify the information about the linked redis server
  2. applicationContext.xml configures connection pools, connection factories, etc. all of the above are for RedisTemplate service. This class provides common methods to access Redis. Then inject the instance of the RedisTemplate class into the RedisUtil tool class for easy calling
  3. Tool class
    package com.dam;
    
     
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.util.CollectionUtils;
    	 
    	/**
    	 * redisTemplate tool class based on spring and redis
    	 * Methods that start with h for all hash es
    	 * For all sets that start with s, there is no general method
    	 * Methods that start with l for all lists
    	 */
    	public class RedisUtil {
    	    private RedisTemplate<String, Object> redisTemplate;
    	     
    	    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
    	        this.redisTemplate = redisTemplate;
    	    }
    	    //=============================common============================
    	    /**
    	     * Specify cache expiration time
    	     * @param key key
    	     * @param time Time (seconds)
    	     * @return
    	     */
    	    public boolean expire(String key,long time){
    	        try {
    	            if(time>0){
    	                redisTemplate.expire(key, time, TimeUnit.SECONDS);
    	            }
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Get expiration time according to key
    	     * @param key Key cannot be null
    	     * @return Time (seconds) returns 0 for permanent validity
    	     */
    	    public long getExpire(String key){
    	        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    	    }
    	     
    	    /**
    	     * Determine whether the key exists
    	     * @param key key
    	     * @return true Exist false do not exist
    	     */
    	    public boolean hasKey(String key){
    	        try {
    	            return redisTemplate.hasKey(key);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Delete cache
    	     * @param key One or more values can be passed
    	     */
    	    @SuppressWarnings("unchecked")
    	    public void del(String ... key){
    	        if(key!=null&&key.length>0){
    	            if(key.length==1){
    	                redisTemplate.delete(key[0]);
    	            }else{
    	                redisTemplate.delete(CollectionUtils.arrayToList(key));
    	            }
    	        }
    	    }
    	     
    	    //============================String=============================
    	    /**
    	     * General cache access
    	     * @param key key
    	     * @return value
    	     */
    	    public Object get(String key){
    	        return key==null?null:redisTemplate.opsForValue().get(key);
    	    }
    	     
    	    /**
    	     * Normal cache put
    	     * @param key key
    	     * @param value value
    	     * @return true Success false failure
    	     */
    	    public boolean set(String key,Object value) {
    	         try {
    	            redisTemplate.opsForValue().set(key, value);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	         
    	    }
    	     
    	    /**
    	     * Normal cache put and set time
    	     * @param key key
    	     * @param value value
    	     * @param time Time (seconds) time should be greater than 0. If time is less than or equal to 0, infinite period will be set
    	     * @return true Success false failure
    	     */
    	    public boolean set(String key,Object value,long time){
    	        try {
    	            if(time>0){
    	                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    	            }else{
    	                set(key, value);
    	            }
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Increase progressively
    	     * @param key key
    	     * @param by How many to add (greater than 0)
    	     * @return
    	     */
    	    public long incr(String key, long delta){ 
    	        if(delta<0){
    	            throw new RuntimeException("Increment factor must be greater than 0");
    	        }
    	        return redisTemplate.opsForValue().increment(key, delta);
    	    }
    	     
    	    /**
    	     * Decrement
    	     * @param key key
    	     * @param by How many to reduce (less than 0)
    	     * @return
    	     */
    	    public long decr(String key, long delta){ 
    	        if(delta<0){
    	            throw new RuntimeException("Decrement factor must be greater than 0");
    	        }
    	        return redisTemplate.opsForValue().increment(key, -delta); 
    	    } 
    	     
    	    //================================Map=================================
    	    /**
    	     * HashGet
    	     * @param key Key cannot be null
    	     * @param item Item cannot be null
    	     * @return value
    	     */
    	    public Object hget(String key,String item){
    	        return redisTemplate.opsForHash().get(key, item);
    	    }
    	     
    	    /**
    	     * Get all key values corresponding to hashKey
    	     * @param key key
    	     * @return Corresponding multiple key values
    	     */
    	    public Map<Object,Object> hmget(String key){
    	        return redisTemplate.opsForHash().entries(key);
    	    }
    	     
    	    /**
    	     * HashSet
    	     * @param key key
    	     * @param map Corresponding to multiple key values
    	     * @return true Success false failure
    	     */
    	    public boolean hmset(String key, Map<String,Object> map){ 
    	        try {
    	            redisTemplate.opsForHash().putAll(key, map);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * HashSet And set the time
    	     * @param key key
    	     * @param map Corresponding to multiple key values
    	     * @param time Time (seconds)
    	     * @return true Success false failure
    	     */
    	    public boolean hmset(String key, Map<String,Object> map, long time){ 
    	        try {
    	            redisTemplate.opsForHash().putAll(key, map);
    	            if(time>0){
    	                expire(key, time);
    	            }
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Put data into a hash table, and if it does not exist, create
    	     * @param key key
    	     * @param item term
    	     * @param value value
    	     * @return true Success false failure
    	     */
    	    public boolean hset(String key,String item,Object value) {
    	         try {
    	            redisTemplate.opsForHash().put(key, item, value);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Put data into a hash table, and if it does not exist, create
    	     * @param key key
    	     * @param item term
    	     * @param value value
    	     * @param time Time (seconds): if the existing hash table has time, the original time will be replaced here
    	     * @return true Success false failure
    	     */
    	    public boolean hset(String key,String item,Object value,long time) {
    	         try {
    	            redisTemplate.opsForHash().put(key, item, value);
    	            if(time>0){
    	                expire(key, time);
    	            }
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Delete values in hash table
    	     * @param key Key cannot be null
    	     * @param item Item can make more than one cannot be null
    	     */
    	    public void hdel(String key, Object... item){ 
    	        redisTemplate.opsForHash().delete(key,item);
    	    }
    	     
    	    /**
    	     * Determine whether there is a value of this item in the hash table
    	     * @param key Key cannot be null
    	     * @param item Item cannot be null
    	     * @return true Exist false do not exist
    	     */
    	    public boolean hHasKey(String key, String item){
    	        return redisTemplate.opsForHash().hasKey(key, item);
    	    }
    	     
    	    /**
    	     * hash If increment does not exist, a new value will be created and returned
    	     * @param key key
    	     * @param item term
    	     * @param by How many to add (greater than 0)
    	     * @return
    	     */
    	    public double hincr(String key, String item,double by){ 
    	        return redisTemplate.opsForHash().increment(key, item, by);
    	    }
    	     
    	    /**
    	     * hash Decrement
    	     * @param key key
    	     * @param item term
    	     * @param by To reduce memory (less than 0)
    	     * @return
    	     */
    	    public double hdecr(String key, String item,double by){ 
    	        return redisTemplate.opsForHash().increment(key, item,-by); 
    	    } 
    	     
    	    //============================set=============================
    	    /**
    	     * Get all the values in the Set according to the key
    	     * @param key key
    	     * @return
    	     */
    	    public Set<Object> sGet(String key){
    	        try {
    	            return redisTemplate.opsForSet().members(key);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return null;
    	        }
    	    }
    	     
    	    /**
    	     * Query from a set according to value, whether it exists
    	     * @param key key
    	     * @param value value
    	     * @return true Exist false do not exist
    	     */
    	    public boolean sHasKey(String key,Object value){
    	        try {
    	            return redisTemplate.opsForSet().isMember(key, value);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Put data into set cache
    	     * @param key key
    	     * @param values Values can be multiple
    	     * @return Success number
    	     */
    	    public long sSet(String key, Object...values) {
    	        try {
    	            return redisTemplate.opsForSet().add(key, values);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return 0;
    	        }
    	    }
    	     
    	    /**
    	     * Put set data into cache
    	     * @param key key
    	     * @param time Time (seconds)
    	     * @param values Values can be multiple
    	     * @return Success number
    	     */
    	    public long sSetAndTime(String key,long time,Object...values) {
    	        try {
    	            Long count = redisTemplate.opsForSet().add(key, values);
    	            if(time>0) expire(key, time);
    	            return count;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return 0;
    	        }
    	    }
    	     
    	    /**
    	     * Get the length of the set cache
    	     * @param key key
    	     * @return
    	     */
    	    public long sGetSetSize(String key){
    	        try {
    	            return redisTemplate.opsForSet().size(key);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return 0;
    	        }
    	    }
    	     
    	    /**
    	     * Remove the value
    	     * @param key key
    	     * @param values Values can be multiple
    	     * @return Number of removed
    	     */
    	    public long setRemove(String key, Object ...values) {
    	        try {
    	            Long count = redisTemplate.opsForSet().remove(key, values);
    	            return count;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return 0;
    	        }
    	    }
    	    //===============================list=================================
    	     
    	    /**
    	     * Get the contents of the list cache
    	     * @param key key
    	     * @param start start
    	     * @param end End 0 to - 1 for all values
    	     * @return
    	     */
    	    public List<Object> lGet(String key,long start, long end){
    	        try {
    	            return redisTemplate.opsForList().range(key, start, end);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return null;
    	        }
    	    }
    	     
    	    /**
    	     * Get the length of the list cache
    	     * @param key key
    	     * @return
    	     */
    	    public long lGetListSize(String key){
    	        try {
    	            return redisTemplate.opsForList().size(key);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return 0;
    	        }
    	    }
    	     
    	    /**
    	     * Get the value in the list by index
    	     * @param key key
    	     * @param index When index > = 0, 0 header, 1 second element, and so on; when index < 0, - 1, footer, - 2 penultimate second element, and so on
    	     * @return
    	     */
    	    public Object lGetIndex(String key,long index){
    	        try {
    	            return redisTemplate.opsForList().index(key, index);
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return null;
    	        }
    	    }
    	     
    	    /**
    	     * Put list in cache
    	     * @param key key
    	     * @param value value
    	     * @param time Time (seconds)
    	     * @return
    	     */
    	    public boolean lSet(String key, Object value) {
    	        try {
    	            redisTemplate.opsForList().rightPush(key, value);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Put list in cache
    	     * @param key key
    	     * @param value value
    	     * @param time Time (seconds)
    	     * @return
    	     */
    	    public boolean lSet(String key, Object value, long time) {
    	        try {
    	            redisTemplate.opsForList().rightPush(key, value);
    	            if (time > 0) expire(key, time);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Put list in cache
    	     * @param key key
    	     * @param value value
    	     * @param time Time (seconds)
    	     * @return
    	     */
    	    public boolean lSet(String key, List<Object> value) {
    	        try {
    	            redisTemplate.opsForList().rightPushAll(key, value);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Put list in cache
    	     * @param key key
    	     * @param value value
    	     * @param time Time (seconds)
    	     * @return
    	     */
    	    public boolean lSet(String key, List<Object> value, long time) {
    	        try {
    	            redisTemplate.opsForList().rightPushAll(key, value);
    	            if (time > 0) expire(key, time);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Modify a piece of data in the list according to the index
    	     * @param key key
    	     * @param index Indexes
    	     * @param value value
    	     * @return
    	     */
    	    public boolean lUpdateIndex(String key, long index,Object value) {
    	        try {
    	            redisTemplate.opsForList().set(key, index, value);
    	            return true;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return false;
    	        }
    	    }
    	     
    	    /**
    	     * Remove N values as value
    	     * @param key key
    	     * @param count How many to remove
    	     * @param value value
    	     * @return Number of removed
    	     */
    	    public long lRemove(String key,long count,Object value) {
    	        try {
    	            Long remove = redisTemplate.opsForList().remove(key, count, value);
    	            return remove;
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            return 0;
    	        }
    	    }
    	     
    	}
    

    4 use

     public static void main(String[] args) throws Exception {
    	        ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 
    	        RedisUtil redisUtil=(RedisUtil) context.getBean("redisUtil");
    	         
    	        //=====================testString======================
    	        redisUtil.set("name", "hello");
    	        System.out.println(redisUtil.get("name"));
    	        redisUtil.del("name");
    	        System.out.println(redisUtil.get("name"));
    	         
    	        //=====================testNumber======================
    	        long incr = redisUtil.incr("number", 1);
    	        System.out.println(incr);
    	        incr =redisUtil.incr("number", 1);
    	        System.out.println(incr);
    	         
    	        //=====================testMap======================       
    	        Map<String,Object> map=new HashMap<>();
    	        map.put("name", "meepo");
    	        map.put("pwd", "password");
    	        redisUtil.hmset("user", map);
     	     //   System.out.println(redisUtil.get("user"));
    	        System.out.println(redisUtil.hget("user","name"));
    	        System.out.println(redisUtil.hget("user", "pwd"));
    	    }

     

 

 

 

 

 

 

 

 

Tags: Redis Java less Database

Posted on Sun, 12 Jan 2020 11:54:28 -0500 by Jakebert