Redis can be understood by looking at this set! For connecting redis with native jedis and integrating redis with spring boot, the actual project uses redis+mysql and redis visualization tool

Posted by dancer on Mon, 17 Jan 2022 05:06:11 +0100

The first part: the native jedis is connected to redis

First, let's understand that we used jdbc to connect to the database when we used mysql. Similarly, when we connect to redis, we need to use jedis.

Step 1: create a new java project and import the package

New java project, import package

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

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

Step 2: open the redis service and write the method

Open redis service

Create a new test class and write a method

public class Ping {
 	public static void main(String[] args) { 
 		Jedis jedis = new Jedis("127.0.0.1",6379);
 		System.out.println("Connection succeeded"); //Check whether the service is running 
 		System.out.println("The service is running: "+jedis.ping());
 	} 
 }

The proof comes with

Step 3: simple operation

Here are some simple jedis for various types of operations

Basic operation api

public class TestPassword { 
public static void main(String[] args) { 
Jedis jedis = new Jedis("127.0.0.1", 6379); 
//Verify the password. If the password is not set, this code is omitted
 // jedis.auth("password"); 
jedis.connect(); //connect 
jedis.disconnect(); //Disconnect 
jedis.flushAll(); //Clear all key s}}

Commands for key operations

public class TestKey { 
public static void main(String[] args) { 
Jedis jedis = new Jedis("127.0.0.1", 6379);
 System.out.println("Clear data:"+jedis.flushDB()); 
 System.out.println("Determine whether a key is:"+jedis.exists("username")); 
 System.out.println("newly added<'username','kuangshen'>Key value pairs:"+jedis.set("username", "kuangshen")); 
 System.out.println("newly added<'password','password'>Key value pairs:"+jedis.set("password", "password")); 
 System.out.print("All keys in the system are as follows:"); 
 Set<String> keys = jedis.keys("*"); 
 System.out.println(keys); 
 System.out.println("Delete key password:"+jedis.del("password"));  
 System.out.println("Judgment key password Is there:"+jedis.exists("password")); 
 System.out.println("View key username Type of value stored:"+jedis.type("username")); 
 System.out.println("Random return key A of space:"+jedis.randomKey()); 
 System.out.println("rename key: "+jedis.rename("username","name")); System.out.println("Take out the modified name: "+jedis.get("name")); System.out.println("Query by index:"+jedis.select(0)); 
 System.out.println("Deletes the selected database from the currently selected database key: "+jedis.flushDB()); 
 System.out.println("Return to the current database key Number of:"+jedis.dbSize()); 
 System.out.println("Delete all in all databases key: "+jedis.flushAll());
  } 
}

Commands for String operations

public class TestString { 
public static void main(String[] args) { 
	Jedis jedis = new Jedis("127.0.0.1", 6379); 
	jedis.flushDB(); 
	System.out.println("===========Add data==========="); 
	System.out.println(jedis.set("key1","value1")); 
	System.out.println(jedis.set("key2","value2")); 
	System.out.println(jedis.set("key3", "value3"));
	System.out.println("Delete key key2:"+jedis.del("key2")); 
	System.out.println("Get key key2:"+jedis.get("key2")); 
	System.out.println("modify key1:"+jedis.set("key1", "value1Changed"));
	 System.out.println("obtain key1 Value of:"+jedis.get("key1")); 
	 System.out.println("stay key3 Add value after:"+jedis.append("key3", "End")); 
	 System.out.println("key3 Value of:"+jedis.get("key3")); 
	 System.out.println("Add multiple key value pairs:"+jedis.mset("key01","value01","key02","value02","key03","value03")); 
	 System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03")); 
	 System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03","key04")); 
	 System.out.println("Delete multiple key value pairs:"+jedis.del("key01","key02")); 
	 System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03"));
	 jedis.flushDB();
	  System.out.println("===========Adding a key value pair prevents overwriting the original value=============="); 
	  System.out.println(jedis.setnx("key1", "value1")); 
	  System.out.println(jedis.setnx("key2", "value2")); 
	  System.out.println(jedis.setnx("key2", "value2-new")); 
	  System.out.println(jedis.get("key1")); 
	  System.out.println(jedis.get("key2")); 
	  System.out.println("===========Add a key value pair and set the effective time============="); 
	  System.out.println(jedis.setex("key3", 2, "value3")); 
	  System.out.println(jedis.get("key3")); 
	  try {
	  	TimeUnit.SECONDS.sleep(3); 
	  } catch (InterruptedException e) {
	   	e.printStackTrace(); 
	   }
	   System.out.println(jedis.get("key3")); 
	   System.out.println("===========Get the original value and update it to the new value=========="); 
	   System.out.println(jedis.getSet("key2", "key2GetSet")); 
	   System.out.println(jedis.get("key2"));
	   System.out.println("get key2 String of values for:"+jedis.getrange("key2", 2, 4));
   } 
 }

Transaction operation

public class TestMulti {
 public static void main(String[] args) {
  //To create a client connection server, the redis server needs to be enabled 
  Jedis jedis = new Jedis("127.0.0.1", 6379); 
  jedis.flushDB(); 
  JSONObject jsonObject = new JSONObject(); 
  jsonObject.put("hello", "world"); 
  jsonObject.put("name", "java"); 
  //Open transaction 
  Transaction multi = jedis.multi(); 
  String result = jsonObject.toJSONString(); 
  try{
	  //Save a piece of data to redis 
	  multi.set("json", result); 
	  //Save another piece of data 
	  multi.set("json2", result); 
	  //An exception is thrown here, with 0 as the dividend 
	  int i = 100/0; 
	  //If no exception is thrown, execute the command entering the queue
	  multi.exec(); 
  }catch(Exception e){ 
  	e.printStackTrace(); 
  	//If an exception occurs, rollback 
  	multi.discard(); 
  }finally{ 
	  System.out.println(jedis.get("json")); 
	  System.out.println(jedis.get("json2"));
	   //Finally shut down the client 
	   jedis.close(); 
   } 
  } 
 }

part 2: spring boot integrates redis

In spring boot, Redis is generally operated using the methods provided by RedisTemplate.
Source code analysis

@Bean
@ConditionalOnMissingBean(name = {"redisTemplate"}) // We can customize a redisTemplate to replace the default one!
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    // The default RedisTemplate does not have too many settings, and redis objects need to be serialized
    // Both generic types are of object type. We need to convert them to < string, Object > for subsequent use
    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;
}

Step 1: import dependencies

Import dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Step 2: yml file configuration

yml file configuration

spring.redis.host=127.0.0.1
spring.redis.port=6379

Step 3: Test

test

@SpringBootTest
class Redis02SpringbootApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("mykey", "I'm a handsome man");
        System.out.println(redisTemplate.opsForValue().get("mykey"));
    }

}

Step 4: customize RedisTemplate

From the source code at the beginning, we can see that SpringBoot automatically generates a RedisTemplate and a StringRedisTemplate in the container. However, the generic type of this RedisTemplate is < object, Object >, which is inconvenient to write code, and many type conversion codes need to be written; We need a RedisTemplate with the generic form < string, Object >. In addition, the RedisTemplate does not set the serialization method of key and value when data exists in Redis. After seeing the @ ConditionalOnMissingBean annotation, you know that if there is a RedisTemplate object in the Spring container, the automatically configured RedisTemplate will not be instantiated. Therefore, we can directly write a configuration class to configure RedisTemplate.
Customize RedisTemplate

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);

        // Serialization configuration
        Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping();
        objectJackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(objectJackson2JsonRedisSerializer);
        template.setHashValueSerializer(objectJackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;
    }
}

Step 5: write a tool class to facilitate operation

Write a Redis tool class (it requires many lines of code to directly operate Redis with RedisTemplate, so it is more convenient to directly encapsulate a RedisUtils. This RedisUtils is handed over to the Spring container for instantiation and annotation injection when used.)
Here are tools written by others, very complete!!!

import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis Tool class*/
public class RedisUtil {
    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public StringRedisTemplate getRedisTemplate() {
        return this.redisTemplate;
    }

    /** -------------------key Related operations--------------------- */

    /**
     * Delete key
     * 
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Batch delete key
     * 
     * @param keys
     */
    public void delete(Collection<String> keys) {
        redisTemplate.delete(keys);
    }

    /**
     * Serialize key
     * 
     * @param key
     * @return
     */
    public byte[] dump(String key) {
        return redisTemplate.dump(key);
    }

    /**
     * Is there a key
     * 
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * Set expiration time
     * 
     * @param key
     * @param timeout
     * @param unit
     * @return
     */
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * Set expiration time
     * 
     * @param key
     * @param date
     * @return
     */
    public Boolean expireAt(String key, Date date) {
        return redisTemplate.expireAt(key, date);
    }

    /**
     * Find matching key
     * 
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * Move the key of the current database to the given database db
     * 
     * @param key
     * @param dbIndex
     * @return
     */
    public Boolean move(String key, int dbIndex) {
        return redisTemplate.move(key, dbIndex);
    }

    /**
     * Remove the expiration time of the key, and the key will be persistent
     * 
     * @param key
     * @return
     */
    public Boolean persist(String key) {
        return redisTemplate.persist(key);
    }

    /**
     * Returns the remaining expiration time of the key
     * 
     * @param key
     * @param unit
     * @return
     */
    public Long getExpire(String key, TimeUnit unit) {
        return redisTemplate.getExpire(key, unit);
    }

    /**
     * Returns the remaining expiration time of the key
     * 
     * @param key
     * @return
     */
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * Randomly return a key from the current database
     * 
     * @return
     */
    public String randomKey() {
        return redisTemplate.randomKey();
    }

    /**
     * Modify the name of the key
     * 
     * @param oldKey
     * @param newKey
     */
    public void rename(String oldKey, String newKey) {
        redisTemplate.rename(oldKey, newKey);
    }

    /**
     * Change the oldKey to newkey only if the newkey does not exist
     * 
     * @param oldKey
     * @param newKey
     * @return
     */
    public Boolean renameIfAbsent(String oldKey, String newKey) {
        return redisTemplate.renameIfAbsent(oldKey, newKey);
    }

    /**
     * Returns the type of value stored by the key
     * 
     * @param key
     * @return
     */
    public DataType type(String key) {
        return redisTemplate.type(key);
    }

    /** -------------------string Related operations--------------------- */

    /**
     * Set the value of the specified key
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * Gets the value of the specified key
     * @param key
     * @return
     */
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * Returns the sub character of the string value in the key
     * @param key
     * @param start
     * @param end
     * @return
     */
    public String getRange(String key, long start, long end) {
        return redisTemplate.opsForValue().get(key, start, end);
    }

    /**
     * Set the value of the given key to value and return the old value of the key
     * 
     * @param key
     * @param value
     * @return
     */
    public String getAndSet(String key, String value) {
        return redisTemplate.opsForValue().getAndSet(key, value);
    }

    /**
     * For the string value stored by the key, obtain the bit on the specified offset
     * 
     * @param key
     * @param offset
     * @return
     */
    public Boolean getBit(String key, long offset) {
        return redisTemplate.opsForValue().getBit(key, offset);
    }

    /**
     * Batch acquisition
     * 
     * @param keys
     * @return
     */
    public List<String> multiGet(Collection<String> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * Set the ASCII code. The ASCII code of string 'a' is 97 and the binary value is' 0110001 '. This method is to change the binary offset bit value to value
     * 
     * @param key position
     * @param value
     *            Value, true is 1, false is 0
     * @return
     */
    public boolean setBit(String key, long offset, boolean value) {
        return redisTemplate.opsForValue().setBit(key, offset, value);
    }

    /**
     * Associate the value value with the key and set the expiration time of the key to timeout
     * 
     * @param key
     * @param value
     * @param timeout
     *            Expiration time
     * @param unit
     *            Time unit, day: timeunit Days hours: timeunit Hours minutes: timeunit MINUTES
     *            Seconds: timeunit Seconds milliseconds: timeunit MILLISECONDS
     */
    public void setEx(String key, String value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    /**
     * The key value can only be set when the key does not exist
     * 
     * @param key
     * @param value
     * @return false has been returned before, and true has not been returned
     */
    public boolean setIfAbsent(String key, String value) {
        return redisTemplate.opsForValue().setIfAbsent(key, value);
    }

    /**
     * Overwrite the string value stored by the given key with the value parameter, starting from the offset
     * 
     * @param key
     * @param value
     * @param offset
     *            Overwrite from specified location
     */
    public void setRange(String key, String value, long offset) {
        redisTemplate.opsForValue().set(key, value, offset);
    }

    /**
     * Gets the length of the string
     * 
     * @param key
     * @return
     */
    public Long size(String key) {
        return redisTemplate.opsForValue().size(key);
    }

    /**
     * Batch add
     * 
     * @param maps
     */
    public void multiSet(Map<String, String> maps) {
        redisTemplate.opsForValue().multiSet(maps);
    }

    /**
     * Set one or more key value pairs at the same time if and only if all given keys do not exist
     * 
     * @param maps
     * @return false has been returned before, and true has not been returned
     */
    public boolean multiSetIfAbsent(Map<String, String> maps) {
        return redisTemplate.opsForValue().multiSetIfAbsent(maps);
    }

    /**
     * Increase (self increase), negative number is self decrease
     * 
     * @param key
     * @return
     */
    public Long incrBy(String key, long increment) {
        return redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * 
     * @param key
     * @return
     */
    public Double incrByFloat(String key, double increment) {
        return redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * Append to end
     * 
     * @param key
     * @param value
     * @return
     */
    public Integer append(String key, String value) {
        return redisTemplate.opsForValue().append(key, value);
    }

    /** -------------------hash Related operations------------------------- */

    /**
     * Gets the value of the specified field stored in the hash table
     * 
     * @param key
     * @param field
     * @return
     */
    public Object hGet(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    /**
     * Gets the value of all the given fields
     * 
     * @param key
     * @return
     */
    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * Gets the value of all the given fields
     * 
     * @param key
     * @param fields
     * @return
     */
    public List<Object> hMultiGet(String key, Collection<Object> fields) {
        return redisTemplate.opsForHash().multiGet(key, fields);
    }

    public void hPut(String key, String hashKey, String value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public void hPutAll(String key, Map<String, String> maps) {
        redisTemplate.opsForHash().putAll(key, maps);
    }

    /**
     * Set only if hashKey does not exist
     * 
     * @param key
     * @param hashKey
     * @param value
     * @return
     */
    public Boolean hPutIfAbsent(String key, String hashKey, String value) {
        return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
    }

    /**
     * Delete one or more hash table fields
     * 
     * @param key
     * @param fields
     * @return
     */
    public Long hDelete(String key, Object... fields) {
        return redisTemplate.opsForHash().delete(key, fields);
    }

    /**
     * Check whether the specified field exists in the hash table key
     * 
     * @param key
     * @param field
     * @return
     */
    public boolean hExists(String key, String field) {
        return redisTemplate.opsForHash().hasKey(key, field);
    }

    /**
     * Add increment to the integer value of the specified field in the hash table key
     * 
     * @param key
     * @param field
     * @param increment
     * @return
     */
    public Long hIncrBy(String key, Object field, long increment) {
        return redisTemplate.opsForHash().increment(key, field, increment);
    }

    /**
     * Add increment to the integer value of the specified field in the hash table key
     * 
     * @param key
     * @param field
     * @param delta
     * @return
     */
    public Double hIncrByFloat(String key, Object field, double delta) {
        return redisTemplate.opsForHash().increment(key, field, delta);
    }

    /**
     * Gets the fields in all hash tables
     * 
     * @param key
     * @return
     */
    public Set<Object> hKeys(String key) {
        return redisTemplate.opsForHash().keys(key);
    }

    /**
     * Gets the number of fields in the hash table
     * 
     * @param key
     * @return
     */
    public Long hSize(String key) {
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * Gets all values in the hash table
     * 
     * @param key
     * @return
     */
    public List<Object> hValues(String key) {
        return redisTemplate.opsForHash().values(key);
    }

    /**
     * Iterates over key value pairs in the hash table
     * 
     * @param key
     * @param options
     * @return
     */
    public Cursor<Entry<Object, Object>> hScan(String key, ScanOptions options) {
        return redisTemplate.opsForHash().scan(key, options);
    }

    /** ------------------------list Related operations---------------------------- */

    /**
     * Get elements in the list by index
     * 
     * @param key
     * @param index
     * @return
     */
    public String lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     * Gets the elements within the specified range of the list
     * 
     * @param key
     * @param start
     *            Start position, 0 is the start position
     * @param end
     *            End position, - 1 returns all
     * @return
     */
    public List<String> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * Stored in the list header
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lLeftPush(String key, String value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lLeftPushAll(String key, String... value) {
        return redisTemplate.opsForList().leftPushAll(key, value);
    }

    /**
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lLeftPushAll(String key, Collection<String> value) {
        return redisTemplate.opsForList().leftPushAll(key, value);
    }

    /**
     * Join only when the list exists
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lLeftPushIfPresent(String key, String value) {
        return redisTemplate.opsForList().leftPushIfPresent(key, value);
    }

    /**
     * If pivot exists, add it before pivot
     * 
     * @param key
     * @param pivot
     * @param value
     * @return
     */
    public Long lLeftPush(String key, String pivot, String value) {
        return redisTemplate.opsForList().leftPush(key, pivot, value);
    }

    /**
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lRightPush(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lRightPushAll(String key, String... value) {
        return redisTemplate.opsForList().rightPushAll(key, value);
    }

    /**
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lRightPushAll(String key, Collection<String> value) {
        return redisTemplate.opsForList().rightPushAll(key, value);
    }

    /**
     * Add a value to an existing list
     * 
     * @param key
     * @param value
     * @return
     */
    public Long lRightPushIfPresent(String key, String value) {
        return redisTemplate.opsForList().rightPushIfPresent(key, value);
    }

    /**
     * Add a value to the right of the pivot element
     * 
     * @param key
     * @param pivot
     * @param value
     * @return
     */
    public Long lRightPush(String key, String pivot, String value) {
        return redisTemplate.opsForList().rightPush(key, pivot, value);
    }

    /**
     * Sets the value of a list element by index
     * 
     * @param key
     * @param index
     *            position
     * @param value
     */
    public void lSet(String key, long index, String value) {
        redisTemplate.opsForList().set(key, index, value);
    }

    /**
     * Move out and get the first element of the list
     * 
     * @param key
     * @return Deleted element
     */
    public String lLeftPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * Move out and get the first element of the list. If there is no element in the list, the list will be blocked until the waiting timeout or pop-up element is found
     * 
     * @param key
     * @param timeout
     *            waiting time
     * @param unit
     *            Time unit
     * @return
     */
    public String lBLeftPop(String key, long timeout, TimeUnit unit) {
        return redisTemplate.opsForList().leftPop(key, timeout, unit);
    }

    /**
     * Remove and get the last element of the list
     * 
     * @param key
     * @return Deleted element
     */
    public String lRightPop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    /**
     * Move out and get the last element of the list. If there is no element in the list, the list will be blocked until the waiting timeout or pop-up element is found
     * 
     * @param key
     * @param timeout
     *            waiting time
     * @param unit
     *            Time unit
     * @return
     */
    public String lBRightPop(String key, long timeout, TimeUnit unit) {
        return redisTemplate.opsForList().rightPop(key, timeout, unit);
    }

    /**
     * Removes the last element of the list, adds it to another list, and returns
     * 
     * @param sourceKey
     * @param destinationKey
     * @return
     */
    public String lRightPopAndLeftPush(String sourceKey, String destinationKey) {
        return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
                destinationKey);
    }

    /**
     * Pop up a value from the list, insert the pop-up element into another list and return it; If the list has no elements, the list is blocked until the wait times out or a pop-up element is found
     * 
     * @param sourceKey
     * @param destinationKey
     * @param timeout
     * @param unit
     * @return
     */
    public String lBRightPopAndLeftPush(String sourceKey, String destinationKey,
            long timeout, TimeUnit unit) {
        return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
                destinationKey, timeout, unit);
    }

    /**
     * Delete the element with value equal to value in the set
     * 
     * @param key
     * @param index
     *            index=0, Delete all elements with value equal to value; Index > 0, delete the first element with value equal to value from the header;
     *            index<0, Delete the first element with value equal to value from the tail;
     * @param value
     * @return
     */
    public Long lRemove(String key, long index, String value) {
        return redisTemplate.opsForList().remove(key, index, value);
    }

    /**
     * Crop list
     * 
     * @param key
     * @param start
     * @param end
     */
    public void lTrim(String key, long start, long end) {
        redisTemplate.opsForList().trim(key, start, end);
    }

    /**
     * Get list length
     * 
     * @param key
     * @return
     */
    public Long lLen(String key) {
        return redisTemplate.opsForList().size(key);
    }

    /** --------------------set Related operations-------------------------- */

    /**
     * set Add element
     * 
     * @param key
     * @param values
     * @return
     */
    public Long sAdd(String key, String... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    /**
     * set Removing Elements 
     * 
     * @param key
     * @param values
     * @return
     */
    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    /**
     * Removes and returns a random element of the collection
     * 
     * @param key
     * @return
     */
    public String sPop(String key) {
        return redisTemplate.opsForSet().pop(key);
    }

    /**
     * Move the element value from one set to another
     * 
     * @param key
     * @param value
     * @param destKey
     * @return
     */
    public Boolean sMove(String key, String value, String destKey) {
        return redisTemplate.opsForSet().move(key, value, destKey);
    }

    /**
     * Gets the size of the collection
     * 
     * @param key
     * @return
     */
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    /**
     * Determine whether the set contains value
     * 
     * @param key
     * @param value
     * @return
     */
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    /**
     * Gets the intersection of two sets
     * 
     * @param key
     * @param otherKey
     * @return
     */
    public Set<String> sIntersect(String key, String otherKey) {
        return redisTemplate.opsForSet().intersect(key, otherKey);
    }

    /**
     * Gets the intersection of the key set and multiple sets
     * 
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sIntersect(String key, Collection<String> otherKeys) {
        return redisTemplate.opsForSet().intersect(key, otherKeys);
    }

    /**
     * key The intersection of the set and the otherKey set is stored in the destKey set
     * 
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long sIntersectAndStore(String key, String otherKey, String destKey) {
        return redisTemplate.opsForSet().intersectAndStore(key, otherKey,
                destKey);
    }

    /**
     * key The intersection of a collection and multiple collections is stored in the destKey collection
     * 
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long sIntersectAndStore(String key, Collection<String> otherKeys,
            String destKey) {
        return redisTemplate.opsForSet().intersectAndStore(key, otherKeys,
                destKey);
    }

    /**
     * Gets the union of two sets
     * 
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sUnion(String key, String otherKeys) {
        return redisTemplate.opsForSet().union(key, otherKeys);
    }

    /**
     * Gets the union of the key set and multiple sets
     * 
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sUnion(String key, Collection<String> otherKeys) {
        return redisTemplate.opsForSet().union(key, otherKeys);
    }

    /**
     * key The union of collection and otherKey collection is stored in destKey
     * 
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long sUnionAndStore(String key, String otherKey, String destKey) {
        return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
    }

    /**
     * key The union of sets and multiple sets is stored in destKey
     * 
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long sUnionAndStore(String key, Collection<String> otherKeys,
            String destKey) {
        return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
    }

    /**
     * Gets the difference set of two sets
     * 
     * @param key
     * @param otherKey
     * @return
     */
    public Set<String> sDifference(String key, String otherKey) {
        return redisTemplate.opsForSet().difference(key, otherKey);
    }

    /**
     * Gets the difference set between the key set and multiple sets
     * 
     * @param key
     * @param otherKeys
     * @return
     */
    public Set<String> sDifference(String key, Collection<String> otherKeys) {
        return redisTemplate.opsForSet().difference(key, otherKeys);
    }

    /**
     * key The difference between the set and the otherKey set is stored in destKey
     * 
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long sDifference(String key, String otherKey, String destKey) {
        return redisTemplate.opsForSet().differenceAndStore(key, otherKey,
                destKey);
    }

    /**
     * key The difference set between a set and multiple sets is stored in destKey
     * 
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long sDifference(String key, Collection<String> otherKeys,
            String destKey) {
        return redisTemplate.opsForSet().differenceAndStore(key, otherKeys,
                destKey);
    }

    /**
     * Get all elements of the collection
     * 
     * @param key
     * @return
     */
    public Set<String> setMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * Gets an element in the collection at random
     * 
     * @param key
     * @return
     */
    public String sRandomMember(String key) {
        return redisTemplate.opsForSet().randomMember(key);
    }

    /**
     * Randomly get count elements in the collection
     * 
     * @param key
     * @param count
     * @return
     */
    public List<String> sRandomMembers(String key, long count) {
        return redisTemplate.opsForSet().randomMembers(key, count);
    }

    /**
     * Randomly get count elements in the collection and remove duplicates
     * 
     * @param key
     * @param count
     * @return
     */
    public Set<String> sDistinctRandomMembers(String key, long count) {
        return redisTemplate.opsForSet().distinctRandomMembers(key, count);
    }

    /**
     * 
     * @param key
     * @param options
     * @return
     */
    public Cursor<String> sScan(String key, ScanOptions options) {
        return redisTemplate.opsForSet().scan(key, options);
    }

    /**------------------zSet Related operations--------------------------------*/
    
    /**
     * When adding elements, the ordered set is arranged from small to large according to the score value of the elements
     * 
     * @param key
     * @param value
     * @param score
     * @return
     */
    public Boolean zAdd(String key, String value, double score) {
        return redisTemplate.opsForZSet().add(key, value, score);
    }

    /**
     * 
     * @param key
     * @param values
     * @return
     */
    public Long zAdd(String key, Set<TypedTuple<String>> values) {
        return redisTemplate.opsForZSet().add(key, values);
    }

    /**
     * 
     * @param key
     * @param values
     * @return
     */
    public Long zRemove(String key, Object... values) {
        return redisTemplate.opsForZSet().remove(key, values);
    }

    /**
     * Increase the score value of the element and return the increased value
     * 
     * @param key
     * @param value
     * @param delta
     * @return
     */
    public Double zIncrementScore(String key, String value, double delta) {
        return redisTemplate.opsForZSet().incrementScore(key, value, delta);
    }

    /**
     * Returns the ranking of elements in the set. The ordered set is arranged from small to large according to the score value of elements
     * 
     * @param key
     * @param value
     * @return 0 Indicates the first place
     */
    public Long zRank(String key, Object value) {
        return redisTemplate.opsForZSet().rank(key, value);
    }

    /**
     * Returns the ranking of elements in the collection, sorted by the score value of elements from large to small
     * 
     * @param key
     * @param value
     * @return
     */
    public Long zReverseRank(String key, Object value) {
        return redisTemplate.opsForZSet().reverseRank(key, value);
    }

    /**
     * Gets the elements of the collection, sorted from small to large
     * 
     * @param key
     * @param start
     *            Start position
     * @param end
     *            End position, - 1 query all
     * @return
     */
    public Set<String> zRange(String key, long start, long end) {
        return redisTemplate.opsForZSet().range(key, start, end);
    }

    /**
     * Get the collection elements and get the score value as well
     * 
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<TypedTuple<String>> zRangeWithScores(String key, long start,
            long end) {
        return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
    }

    /**
     * Query collection elements according to Score value
     * 
     * @param key
     * @param min
     *            minimum value
     * @param max
     *            Maximum
     * @return
     */
    public Set<String> zRangeByScore(String key, double min, double max) {
        return redisTemplate.opsForZSet().rangeByScore(key, min, max);
    }

    /**
     * Query the collection elements according to the Score value, and sort them from small to large
     * 
     * @param key
     * @param min
     *            minimum value
     * @param max
     *            Maximum
     * @return
     */
    public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
            double min, double max) {
        return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
    }

    /**
     * 
     * @param key
     * @param min
     * @param max
     * @param start
     * @param end
     * @return
     */
    public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
            double min, double max, long start, long end) {
        return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
                start, end);
    }

    /**
     * Gets the elements of the collection, sorted from large to small
     * 
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zReverseRange(String key, long start, long end) {
        return redisTemplate.opsForZSet().reverseRange(key, start, end);
    }

    /**
     * Get the elements of the collection, sort them from large to small, and return the score value
     * 
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<TypedTuple<String>> zReverseRangeWithScores(String key,
            long start, long end) {
        return redisTemplate.opsForZSet().reverseRangeWithScores(key, start,
                end);
    }

    /**
     * Query the collection elements according to the Score value, and sort them from large to small
     * 
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Set<String> zReverseRangeByScore(String key, double min,
            double max) {
        return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
    }

    /**
     * Query the collection elements according to the Score value, and sort them from large to small
     * 
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Set<TypedTuple<String>> zReverseRangeByScoreWithScores(
            String key, double min, double max) {
        return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
                min, max);
    }

    /**
     * 
     * @param key
     * @param min
     * @param max
     * @param start
     * @param end
     * @return
     */
    public Set<String> zReverseRangeByScore(String key, double min,
            double max, long start, long end) {
        return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max,
                start, end);
    }

    /**
     * Get the number of collection elements according to the score value
     * 
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Long zCount(String key, double min, double max) {
        return redisTemplate.opsForZSet().count(key, min, max);
    }

    /**
     * Get collection size
     * 
     * @param key
     * @return
     */
    public Long zSize(String key) {
        return redisTemplate.opsForZSet().size(key);
    }

    /**
     * Get collection size
     * 
     * @param key
     * @return
     */
    public Long zZCard(String key) {
        return redisTemplate.opsForZSet().zCard(key);
    }

    /**
     * Gets the score value of the value element in the collection
     * 
     * @param key
     * @param value
     * @return
     */
    public Double zScore(String key, Object value) {
        return redisTemplate.opsForZSet().score(key, value);
    }

    /**
     * Removes the member at the specified index location
     * 
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Long zRemoveRange(String key, long start, long end) {
        return redisTemplate.opsForZSet().removeRange(key, start, end);
    }

    /**
     * Removes members based on the range of the specified score value
     * 
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Long zRemoveRangeByScore(String key, double min, double max) {
        return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
    }

    /**
     * Get the union of key and otherKey and store it in destKey
     * 
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long zUnionAndStore(String key, String otherKey, String destKey) {
        return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
    }

    /**
     * 
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long zUnionAndStore(String key, Collection<String> otherKeys,
            String destKey) {
        return redisTemplate.opsForZSet()
                .unionAndStore(key, otherKeys, destKey);
    }

    /**
     * intersection
     * 
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long zIntersectAndStore(String key, String otherKey,
            String destKey) {
        return redisTemplate.opsForZSet().intersectAndStore(key, otherKey,
                destKey);
    }

    /**
     * intersection
     * 
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long zIntersectAndStore(String key, Collection<String> otherKeys,
            String destKey) {
        return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
                destKey);
    }

    /**
     * 
     * @param key
     * @param options
     * @return
     */
    public Cursor<TypedTuple<String>> zScan(String key, ScanOptions options) {
        return redisTemplate.opsForZSet().scan(key, options);
    }
}

Step 6: test with tool class

test

@SpringBootTest
class Redis02SpringbootApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        redisUtil.set("mykey", "I'm a handsome man");
        System.out.println(redisUtil.get("mykey"));
    }

}

The third part: the actual project uses redis+mysql

Step 1: Guide Package

<dependency>
     <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Step 2: change the yml configuration file

Add the redis configuration to the original mysql configuration

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/book?useSSL=false
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

  redis:
    # Redis database index (0 by default)
    database: 0
    # Host host, the default is localhost
    host: 127.0.0.1
    # Port number, 6379 by default
    port: 6379
    # Password, blank by default
    password:
    # Connection pool
    jedis:
      pool:
        # Maximum number of connections in the connection pool (negative value indicates no limit)
        max-active: 8
        # Minimum free connections in connection pool
        min-idle: 0
        # Maximum free connections in the connection pool
        max-idle: 8
        # Maximum blocking wait time of connection pool (negative value indicates no limit)
        max-wait: -1
    # Connection timeout (MS)
    timeout: 5000

Step 3: serialize the data to be transmitted

Step 4: write redisconfig configuration file

RedisConfiguration (serialization must be configured, otherwise json format will be cached in redis and garbled; the serialization configuration of Springboot1.x and 2.x versions is also different, which needs special attention)

package com.hzf.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;

@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * In the cache object collection, the cache is saved in the form of key value. When the cached key is not specified, SpringBoot uses the SimpleKeyGenerator to generate the key.
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).build();
        return redisCacheManager;
    }

    /**
     * @return Return type
     * @Description: Prevent the serialization of redis from being garbled
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());//key serialization
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));  //value serialization

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

Step 5: use cache in my original project controller

annotationeffect
@CacheableBefore the method is executed, Spring checks whether there is data in the cache. If there is data, it directly returns the cached data; If not, call the method and put the method return value into the cache.
@CachePutPut the return value of the method into the cache.
@CacheEvictDelete the data in the cache.

Here, I add @ Cacheable annotation to the data returned by a method of my controller layer, that is, the data after the first query will be put into redis, and we will not continue mysql query

For the detailed explanation of @ Cacheable annotation, see other bloggers
https://blog.csdn.net/qq_31404603/article/details/88081039

//Home page recommended books
    @Cacheable(value = "recommendbooks")
    @RequestMapping(value = "/recommendBook", method = {RequestMethod.GET})
    public ServerResponse recommendBook(){
     	System.out.println("This information will be displayed for the first query");
        bookService.updaterecommend();
        List<Book> books = bookService.recommendBook();
        if(books != null){
            return ServerResponse.success("Operation succeeded").data("recommendbooks",books);
        }
        return ServerResponse.error("operation failed");

    }

Step 5: enable the use cache on the startup class

@Enable caching annotation configuration enable caching

Step 6: Test

Start the project and access the cached method of the controller layer
The data displayed on the web page is as follows:

Rear console display:

After that, no matter how to refresh the request, the console does not output that sentence, and only queries it once
To see whether redis has been saved, we can directly use the command line

keys * Find all key
get key Find a data

It can also be viewed through visualization tools
Look at the fourth part

part 4: redis visualization tool

Redis is used in the project. I want to query the data in redis and always want to find a visualization tool. Today I found Redis Desktop Manager and tried it. It's very easy to use.

Step 1: Download

Redis Desktop Manager is open source and can be downloaded from github. But if you want to use it on windows, you need to install the package.
Download from the official website: https://redisdesktop.com/download
GitHub address: https://github.com/uglide/RedisDesktopManager/releases
You need to subscribe to the official website address download. It costs money. Forget it.
I found a free cloud disk in the evening:
Baidu online disk: http://pan.baidu.com/s/1kU8sY3P

Step 2: installation

exe file, just next all the way

Step 3: use

To connect to the redis server:


The premise of connecting here is that the redis service you want to connect to has been started

Step 4: look at examples

Based on the actual project data of the third part
You can see the data stored in redis. If it is deleted, the next request will first find out whether there is data in redis. If there is, it will be returned directly. If not, check the data from mysql again and put it in redis.

Topics: Java Redis Spring Boot