Redis quick start and Application

1, Redis overview

Redis is an open source high-performance memory based key value pair NoSQL database developed in C language. Compared with the relational database that must be stored according to the specified format, the data format of non relational database is more flexible, which is usually used to check the storage of large-scale data.

Redis is a kind of non relational database. It is based on memory and the data structure is k-v. Mainly used for caching. Redis is single threaded. In the case of multi-user concurrent operation, it processes one request in sequence and then another request. Data persistence and Master-Slave replication can be realized. In addition to the basic K-V structure, it also supports more complex structures. As long as the master slave policy is enabled, data backup can be realized. Its concurrency can reach 60000 or 70000.

In high concurrency scenarios, if you need to constantly check the MySQL database to get the same data, repeated and continuous read and write operations will lead to high disk IO and poor concurrency. However, after Redis caches the frequently used data, the request will directly query the data in Redis to reduce the database load and effectively improve the program response speed.

2, Redis download and installation

Windows installation: https://github.com/dmajkic/redis/releases
Official website:
Chinese official website: http://redis.cn/topics/introduction
English official website: http://redis.io/topics/introduction
​ redis-benchmark.exe test performance
​ redis-check-aof.exe test persistence
​ redis-cli.exe client
​ redis-server.exe server

3, Redis startup

  1. redis is not started in the background by default. Modify this conf file
    Start daemon: Line 223
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize no   #Change no to yes to start the daemon daemon daemon
  1. Start the redis service and specify the conf file to start
redis-server XXX/redis.conf 
  1. Connect using redis cli
redis-cli -p 6379
  1. Check whether the redis process is started
ps -ef|grep redis


Redis related knowledge:

(1) Redis has 16 databases by default. The database number starts from 0. The database number 0 is used by default. The number of conf configuration files can be modified.

(2) Use select database number to switch the database used

(3) The dbsize command is used to view the number of key s in the current database

(4) keys * command to view all key s in the current database

(5) Flush DB command clears the current database

(6) The flush command empties all databases

(7) All databases in redis use the same password. There is no password by default. Redis believes that the security level should be guaranteed by Linux

(8) All indexes in Redis start from 0

(9) The default port of Redis is 6379

4, Redis five data types and operations

    1. redis Data structure:
        redis Stored are: key,value Format data.
        among key All strings, value There are five different data structures
        value Data structure:
                1) String type string
                2) Hash type hash :  map format 
                3) List type list :  linkedlist Format. Duplicate elements are supported
                4) Collection type set  :  Duplicate elements are not allowed
                5) Ordered set type sortedset: Duplicate elements are not allowed and have order

    2. String type string
        1. Storage: set key value
            127.0.0.1:6379> set username zhangsan
            OK
        2. obtain: get key
            127.0.0.1:6379> get username
            "zhangsan"
        3. Delete: del key
            127.0.0.1:6379> del age
            (integer) 1
    3. Hash type hash
        1. Storage: hset key field value
            127.0.0.1:6379> hset myhash username lisi
            (integer) 1
            127.0.0.1:6379> hset myhash password 123
            (integer) 1
        2. obtain:
            * hget key field: Gets the specified field Corresponding value
                127.0.0.1:6379> hget myhash username
                "lisi"
            * hgetall key: Get all field and value
                127.0.0.1:6379> hgetall myhash
                1) "username"
                2) "lisi"
                3) "password"
                4) "123"

        3. Delete: hdel key field
            127.0.0.1:6379> hdel myhash username
            (integer) 1

    4. List type list:
    You can add an element to the head (left) or tail (right) of the list
        1. add to:
            1. lpush key value: Add elements to the left table of the list

            2. rpush key value: Add elements to the right of the list

                127.0.0.1:6379> lpush myList a
                (integer) 1
                127.0.0.1:6379> lpush myList b
                (integer) 2
                127.0.0.1:6379> rpush myList c
                (integer) 3
        2. obtain:
            * lrange key start end : Range acquisition
                127.0.0.1:6379> lrange myList 0 -1
                1) "b"
                2) "a"
                3) "c"
        3. Delete:
            * lpop key:  Delete the leftmost element of the list and return the element
            * rpop key:  Deletes the rightmost element of the list and returns the element
            * lrem key count value : delete key lower count Quantitative value element
        4. Get number:
            * llen key:  Get the number of elements
            		 
    6. Collection type set :  Duplicate elements are not allowed
        1. Storage: sadd key value
            127.0.0.1:6379> sadd myset a
            (integer) 1
            127.0.0.1:6379> sadd myset a
            (integer) 0
        2. obtain: smembers key:obtain set All elements in the collection
            127.0.0.1:6379> smembers myset
            1) "a"
        3. Delete: srem key value:delete set An element in a collection   
            127.0.0.1:6379> srem myset a
            (integer) 1
        4. Number of fetches:
            * scard key:  Get the number of elements              
              
    7. Ordered set type sortedset: 
    [ps:Duplicate elements are not allowed and have order.
    Each element is associated with a double Score of type.
    redis It is through scores that the members in the set are sorted from small to large.]

        1. Storage: zadd key score value
            127.0.0.1:6379> zadd mysort 60 zhangsan
            (integer) 1
            127.0.0.1:6379> zadd mysort 50 lisi
            (integer) 1
            127.0.0.1:6379> zadd mysort 80 wangwu
            (integer) 1
        2. obtain: zrange key start end [withscores]
            127.0.0.1:6379> zrange mysort 0 -1
            1) "lisi"
            2) "zhangsan"
            3) "wangwu"

            127.0.0.1:6379> zrange mysort 0 -1 withscores
            1) "zhangsan"
            2) "60"
            3) "wangwu"
            4) "80"
            5) "lisi"
            6) "500"
        3. Delete: zrem key value
            127.0.0.1:6379> zrem mysort lisi
            (integer) 1
        4. Get number:
            * zcard key:  Get the number of elements     
            
    8. General Command
        1. keys * : Query all keys
        2. type key :  Get the corresponding key value Type of
        3. del key: Delete the specified key value

5, Redis persistence

redis is an in memory database. If there is no persistence, data downtime will be lost.

Persistence concept: the working mechanism of using disk to save data and recover the saved data at a specific time is called persistence.

There are two ways of persistence:

(1) Snapshot

Save the working state at a certain time point, and you can directly restore the working state at the specified time point during recovery. This method in Redis is called RDB.

Modify the name of the file where the data is saved in memory. The default name is dump rdb

rdb save directory

<1> Use the bgsave command to save kv to rdb file:

This command can be saved manually and executed in the background. redis service can continue to execute subsequent instructions, which is widely used.

Working principle of bgsave instruction:

<2> Automatically save the configuration (redis needs to be restarted after modifying the configuration file)

In the conf file, take "save 900 1" as the description. A key change (referring to addition, deletion and modification) is found within 900s. For Linux, fork() is a process to save the k-v value in dump DB.

RDB disadvantages:
(1) Based on the idea of snapshot, all data is read and written every time. When the amount of data is large, the efficiency is very low
(2) Creating subprocesses based on fork causes additional memory consumption
(3) Downtime brings the risk of data loss (data may not be saved at a certain point in time)

(2) Log

Record the commands of all operations on the data, and re execute these commands when recovering the data. This method in Redis is called AOF.

appendonly no  #aof mode is not enabled by default. rdb persistence is used by default. In most cases, rdb is sufficient! Change to yes to enable aof function
appendfilename "appendonly.aof"  # The name of the persistent file

# appendfsync always  # Each modification consumes sync performance
appendfsync everysec  # sync is executed once per second, and the data of this second may be lost
# appendfsync no      # Do not execute sync. The operating system synchronizes data by itself, which is the fastest, but it is generally not used.


As shown in the figure above:
You can only add files, but you can't overwrite files, so the files will be larger and larger. If the aof file is larger than 64M. fork a new process to rewrite the file.
At the beginning of redis startup, the file will be read to rebuild the data, and the write instruction will be executed from front to back according to the contents of the log file to complete the data recovery (it is very slow for big data).

If there is an error in the aof file, redis will not be able to start. You need to repair the aof file. Redis provides a tool redis check aof -- fix

Steps to simulate aof errors and repair them:
1.shutdown exit to exit redis
2. Delete data / dump RDB file, because it contains stored data
3.vim appendonly.aof, arbitrarily modify and save
4. Try to start redis, and an error is reported when logging in to cli:
Could not connect to Redis at node1:6379: Connection refused
5. Execute the repair tool: redis check AOF -- fix... / data / appendonly aof
6. You need to confirm, enter y, and the repair is successful. Successfully truncated AOF
7. Execute again. If the aof file is normal, you will find that the data has been recovered

[ps: if the aof file is damaged, adding data at the bottom of the aof file can be repaired, but if the structure of set k1 v1 is damaged, aof cannot be repaired, and the directly empty database is repaired.]

Recommendations for official use:
Generally, to provide high data security, it is recommended to use two persistence methods at the same time. If you can accept a few minutes of data loss caused by a disaster, you can use RDB only. Many users only use AOF, but we suggest that since RDB can take a complete snapshot of the data from time to time and provide faster restart, it is best to also use RDB.

6, redis client Jedis and Luttuce

Both lettue and Jedis are Redis clients and can directly connect to the redis server

(1)Jedis

Jedis is a direct connected redis server in implementation, which is non thread safe in multi-threaded environment. At this time, use connection pool to add physical connection for each jedis instance.

(2)Lettuce

The connection of lattice is based on netty. The connection instance StatefulRedisConnection can be accessed concurrently among multiple threads. Because StatefulRedisConnection is thread safe, a connection instance (i.e. StatefulRedisConnection) can meet concurrent access in a multi-threaded environment. This is a scalable design. If a connection instance is not enough, you can also add connection instances as needed. Lettuce mainly uses netty to realize synchronous and asynchronous communication with redis.

7, Integrating redis clients with springboot: Jedis and Luttuce

When you use springboot to connect to redis, use springboot 1.0 The X version uses Jedis by default, but in spring boot 2 The X version uses Lettuce by default.
[ps: no matter what client is used, objects stored in redis must be serialized]

(1)SpringBoot2.X Integrated lattice connection pool:

<1> Dependency:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <!--lettuce pool Connection pool-->
            <artifactId>commons-pool2</artifactId>
        </dependency>

<2> application. Properties configuration file

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=root
# The maximum number of connections in the connection pool (a negative value indicates no limit) defaults to 8
spring.redis.lettuce.pool.max-active=8
# The maximum blocking waiting time of connection pool (negative value indicates no limit) is - 1 by default
spring.redis.lettuce.pool.max-wait=-1ms
# The maximum free connections in the connection pool are 8 by default
spring.redis.lettuce.pool.max-idle=8
# The minimum free connection in the connection pool defaults to 0
spring.redis.lettuce.pool.min-idle=0

<3> Configure redis configuration class and customize RedisTemplate:

Customize RedisTemplate and set serializer to facilitate the operation of instance objects.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

<4> Define test entity classes

public class User implements Serializable {
    private static final long serialVersionUID = 4220515347228129741L;
    private Integer id;
    private String username;
 
    public User(Integer id, String username) {
        this.id = id;
        this.username = username;
    }
 
    public User() {
    }
    //getter/setter omitted
}

<5> Testing

//@RunWith(SpringRunner.class) means running in the spring environment. At this time, @ Aurowried will be able to inject RedisTemplate
@RunWith(SpringRunner.class)  
@SpringBootTest
public class RedisTest {
    private Logger logger = LoggerFactory.getLogger(RedisTest.class);
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
 
    @Test
    public void test() {
        String key = "user:1"; //Hierarchical naming, defined according to business scenarios
        redisTemplate.opsForValue().set(key, new User(1,"Huamanlou"));
        User user = (User) redisTemplate.opsForValue().get(key);
        logger.info("uesr: "+user.toString());
    }
}

(2)SpringBoot2.X consolidated Jedis:

Because springboot2 The "default" in 0 is to use lattice to integrate Redis services. Spring boot starter data Redis only introduces lattice package by default, not jedis package support. Therefore, you need to manually introduce the package of jedis and exclude the package of lettuce.
<1> Dependent configuration:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
     <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
       <groupId>redis.clients</groupId>
       <artifactId>jedis</artifactId>
       <version>2.9.0</version>
</dependency>

<2>application. Properties configuration, using jedis connection pool

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=root
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.jedis.pool.max-active=8

<3> Configure redis configuration class and customize RedisTemplate. The connection object used by Jedis template is JedisConnectionFactory, which needs to be manually configured and noted.
springboot2.x integration Jedis does not read spring. X in the configuration file redis. For such configurations as host, you need to manually set the value for Factory.

@Configuration
public class RedisConfig2 {
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
    //In springboot 2 In version x, RedisStandaloneConfiguration class is recommended to set the port, address and other attributes of the connection.
    //Because the JedisConnectionFactory method of setting up the connection is outdated
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        //Manual setting value
        config.setHostName(host);
        config.setPort(port);
        config.setPassword(RedisPassword.of(password));
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(config);
        return connectionFactory;
    }
    
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(JedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }
}

(3) Why customize the rredisstemplate?

After the dependency of redis is introduced, the RredisTemplate will be automatically configured and can be directly injected into the RedisTemplate for use. Look at the source code:
Spring Boot automatically generates a RedisTemplate and a StringRedisTemplate in the container. However, the generic type of this RedisTemplate is < object, Object >. In this way, it is very inconvenient to write code. You have to write a lot of type conversion code.

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
 
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
}

Because of the @ ConditionalOnMissingBean(name = "redisTemplate") annotation,
Therefore, if we customize a RedisTemplate object name d "RedisTemplate" in the Spring container, the automatically configured RedisTemplate will not be instantiated.
[Note: just like this, the name of the customized redisTemplate method in chapter (1) (2) must be called "redisTemplate", because the @ bean annotation configures the name of the bean according to the "method name". At this time, the goal of overwriting the default configuration is achieved]

[example] configure an rredisstemplate

Configure a RedisTemplate whose generic type is < string, Object >.
Set the key value serialization method when the RedisTemplate stores data in Redis
(ps: the default serialization method is JdkSerializationRedisSerializer. When viewing the stored k-v through redis desktop manager, the displayed key value is not a normal character)

@Configuration
public class RedisConfig {
  @Bean
  public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
    RedisTemplate<String,Object> template = new RedisTemplate <>();
    template.setConnectionFactory(factory);
 
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
     
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    // The key is serialized by String
    template.setKeySerializer(stringRedisSerializer);
    // The key of hash is also serialized by String
    template.setHashKeySerializer(stringRedisSerializer);
    // value is serialized by jackson
    template.setValueSerializer(jackson2JsonRedisSerializer);
    // The value serialization method of hash is jackson
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
 
    return template;
  }
}

Redis operation tool class

/**
 * redis Tool class
 **/
 @Component
 public class RedisUtils {
   /**
    * Inject redisTemplate bean
    */
   @Autowired
   private RedisTemplate <String,Object> redisTemplate;
 
   /**
    * 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, which means it is permanently valid
    */
   public long getExpire(String key) {
     return redisTemplate.getExpire(key, TimeUnit.SECONDS);
   }
 
   /**
    * Determine whether the key exists
    *
    * @param key key
    * @return true Exists false does 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 (string)=============================
 
   /**
    * Normal cache fetch
    *
    * @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 in and set time
    *
    * @param key   key
    * @param value value
    * @param time  Time (seconds) time must be greater than 0. If time is less than or equal to 0, the 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;
     }
   }
 
   /**
    * Increasing
    *
    * @param key   key
    * @param delta How many to add (greater than 0)
    * @return
    */
   public long incr(String key, long delta) {
     if (delta < 0) {
       throw new RuntimeException("The increment factor must be greater than 0");
     }
     return redisTemplate.opsForValue().increment(key, delta);
   }
 
   /**
    * Diminishing
    *
    * @param key   key
    * @param delta 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);
   }
   // ================================Hash (hash)=================================
 
   /**
    * 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. If it does not exist, it will be created
    *
    * @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. If it does not exist, it will be created
    *
    * @param key   key
    * @param item  term
    * @param value value
    * @param time  Time (seconds): Note: 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 from hash table
    *
    * @param key  Key cannot be null
    * @param item Item can make multiple non null able
    */
   public void hdel(String key, Object... item) {
     redisTemplate.opsForHash().delete(key, item);
   }
 
   /**
    * Judge 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 Exists false does not exist
    */
   public boolean hHasKey(String key, String item) {
     return redisTemplate.opsForHash().hasKey(key, item);
   }
 
   /**
    * hash If increment does not exist, it will create one and return the added value
    *
    * @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 Diminishing
    *
    * @param key  key
    * @param item term
    * @param by   To reduce (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 Exists false does 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 Number of successful
    */
   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 Number of successful
    */
   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;
     }
   }
 
   /**
    * Gets 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 with 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 represent 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;
     }
   }
 
   /**
    * Gets 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 through the index
    *
    * @param key   key
    * @param index When index index > = 0, 0 header, 1 second element, and so on; When index < 0, - 1, footer, - 2, the penultimate 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 into cache
    *
    * @param key   key
    * @param value value
    * @return
    */
   public boolean lSet(String key, Object value) {
     try {
       redisTemplate.opsForList().rightPush(key, value);
       return true;
     } catch (Exception e) {
       e.printStackTrace();
       return false;
     }
   }
 
   /**
    * Put the list into the 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 into cache
    *
    * @param key   key
    * @param value value
    * @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 into 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 are removed
    * @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;
     }
   }
 }

Keywords: Java Redis Spring Boot Back-end

Added by private_click on Sun, 23 Jan 2022 21:27:38 +0200