RedisTemplate and StringRedisTemplate are provided in spring boot data Redis. StringRedisTemplate is a subclass of RedisTemplate. The two methods are basically the same. The difference is mainly reflected in the different data types of operations. Both generics in RedisTemplate are objects, which means that the stored key and value can be one Object, The two generics of StringRedisTemplate are String, which means that the key and value of StringRedisTemplate can only be strings.
Note: when RedisTemplate is used, objects are serialized into Redis by default, so the placed objects must implement the object serialization interface.
1. Build environment
Build environment: use idea + jdk8 + springboot2 3.5 integrate Redis.
Step 1: use IDEA to build the project and introduce corresponding dependencies at the same time
Dependent selection
Introduce dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.imooc</groupId> <artifactId>springboot-redis-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-redis-demo</name> <description>Demo Redis project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Step 2: configure Redis
application. The YML configuration file is as follows:
# host spring.redis.host=127.0.0.1 # port spring.redis.port=6379 # password spring.redis.password=root # Database, 0 by default spring.redis.database=0 # Maximum number of connections = maxTotal spring.redis.jedis.pool.max-active=8 # Maximum number of free resources allowed in the resource pool spring.redis.jedis.pool.max-idle=8 # The resource pool ensures a minimum number of free connections spring.redis.jedis.pool.min-idle=2 # Connection timeout spring.redis.jedis.pool.max-wait=1000
Step 3: add Redis serialization method
Redis needs to serialize objects so that objects can be stored across platforms and transmitted over the network. Because both storage and network transmission need to save an object state into a byte format recognized by cross platform, and then other platforms can restore the object information through byte information analysis, the data for "cross platform storage" and "network transmission" need to be serialized.
/** * redisTemplate The jdkSerializeable used for serialization stores binary bytecode, so you can customize the serialization class * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // Replace the default serialization with Jackson2JsonRedisSerialize Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // Set serialization rules for key and value redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; }
2. Test Redis
In the test package, write down the test method as follows:
ApplicationTests.java
package com.xiao.springdatademo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; @SpringBootTest class ApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test void testInit() { //PING PONG heartbeat mechanism detects whether the connection is successful String pong = redisTemplate.getConnectionFactory().getConnection().ping(); System.out.println("pong = " + pong); } @Test public void testString(){ // Insert a piece of data redisTemplate.opsForValue().set("username","lisi"); // Get a piece of data Object username = redisTemplate.opsForValue().get("username"); System.out.println("username = " + username); } }
Test successful!
3,StringRedisTemplate
3.1 introduction
-
StringRedisTemplate inherits RedisTemplate.
-
The serialization class used by StringRedisTemplate is StringRedisSerializer.
-
SDR adopts two serialization strategies by default: String serialization strategy and JDK serialization strategy. By default, StringRedisTemplate adopts the serialization strategy of string, and the saved key s and value s are serialized and saved by this strategy.
-
StringRedisTemplate is friendly to string support and cannot store objects. When your redis database originally stores string data or the data you want to access is string type data, you can use StringRedisTemplate.
3.2 common operations of StringRedisTemplate
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//Save data to redis and set cache time stringRedisTemplate.boundValueOps("test").increment(-1);//val do - 1 operation stringRedisTemplate.opsForValue().get("test")//Get the val in the cache according to the key stringRedisTemplate.boundValueOps("test").increment(1);//val +1 stringRedisTemplate.getExpire("test")//Get expiration time according to key stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//Get the expiration time according to the key and convert it to the specified unit stringRedisTemplate.delete("test");//Delete cache according to key stringRedisTemplate.hasKey("546545");//Check whether the key exists and return the boolean value stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//Store the set set in the specified key stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//Set expiration time stringRedisTemplate.opsForSet().isMember("red_123", "1")//Check whether the specified data exists in the collection according to the key stringRedisTemplate.opsForSet().members("red_123");//Get set set according to key
3.3. Use of StringRedisTemplate
Inject stringRedisTemplate with @ Autowired annotation.
package com.xiao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.core.StringRedisTemplate; import java.util.*; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.*; //Start the springboot application @SpringBootTest(classes = RedisDay2Application.class) public class TestStringRedisTemplate { //Inject StringRedisTemplate @Autowired private StringRedisTemplate stringRedisTemplate; //Both key and value are strings //Operation key related @Test public void testKey(){ //stringRedisTemplate.delete("name"); // Delete a key Boolean hasKey = stringRedisTemplate.hasKey("name");//Determine whether a key exists System.out.println(hasKey); DataType name = stringRedisTemplate.type("name");//Determine the type corresponding to the key System.out.println(name); Set<String> keys = stringRedisTemplate.keys("*"); keys.forEach(key-> System.out.println("key = " + key)); Long expire = stringRedisTemplate.getExpire("age");//Get key timeout - 1 never timeout - 2 key does not exist > = 0 expiration time System.out.println(expire); //stringRedisTemplate.rename("name","name1"); // Modify the name to determine whether the key exists stringRedisTemplate.move("name1",1); //You can move to the specified library } //Operate redis String opsForValue. The actual operation is the String type in redis @Test public void testString(){ stringRedisTemplate.opsForValue().set("name","Xiao Chen"); // set sets a key value String value = stringRedisTemplate.opsForValue().get("name"); //Used to get the value corresponding to a key System.out.println("value = " + value); stringRedisTemplate.opsForValue().set("code","2357", 120,TimeUnit.SECONDS); //Set a key timeout stringRedisTemplate.opsForValue().append("name",",It's very kind of him!"); //Add } //Operate the list type opsForList in redis. The actual operation is the list type in redis @Test public void testList(){ stringRedisTemplate.opsForList().leftPush("names","Xiao Chen"); //Create a list and put an element in it stringRedisTemplate.opsForList().leftPushAll("names","Xiao Chen","Xiao Zhang","Xiao Wang"); //Create a list and place multiple elements ArrayList<String> names = new ArrayList<>(); names.add("xiaoming"); names.add("xiaosan"); stringRedisTemplate.opsForList().leftPushAll("names",names); List<String> stringList = stringRedisTemplate.opsForList().range("names", 0, -1); //Traversal list stringList.forEach(value-> System.out.println("value = " + value)); stringRedisTemplate.opsForList().trim("names",1,3); //Intercept the list of the specified interval } //Operate the set type opsForSet in redis. The actual operation is the set type in redis @Test public void testSet(){ stringRedisTemplate.opsForSet().add("sets","Li Si","Wang Wu"); //Create a set and place multiple elements Set<String> sets = stringRedisTemplate.opsForSet().members("sets"); //View members in set sets.forEach(value-> System.out.println("value = " + value)); Long size = stringRedisTemplate.opsForSet().size("sets");//Get the number of set set elements System.out.println("size = " + size); } //Zset type in redis operation @Test public void testZset(){ stringRedisTemplate.opsForZSet().add("zsets","Zhang San",1000); //Create and place elements Set<String> zsets = stringRedisTemplate.opsForZSet().range("zsets", 0, -1);//Specify range query zsets.forEach(value-> System.out.println("value = " + value)); } //Operate the hash type opsForHash in redis. The actual operation is the hash type in redis @Test public void testHash(){ stringRedisTemplate.opsForHash().put("maps","name","Zhang San"); //Create a hash type and put in key value HashMap<String, String> map = new HashMap<String, String>(); map.put("age","18"); map.put("bir","2020-12-12"); stringRedisTemplate.opsForHash().putAll("maps",map); //Put multiple key value s List<Object> values = stringRedisTemplate.opsForHash().multiGet("maps", Arrays.asList("name", "age"));//Get multiple key value s values.forEach(value-> System.out.println("value = " + value)); String value = (String) stringRedisTemplate.opsForHash().get("maps", "name");//Get the value of a key in the hash stringRedisTemplate.opsForHash().values("maps"); //Get all value s Set<Object> keys = stringRedisTemplate.opsForHash().keys("maps");//Get all keys } }
4,RedisTemplate
4.1 introduction
- RedisTemplate adopts the JDK serialization strategy by default, and the saved key s and value s are serialized and saved by this strategy.
- The serialization class used by RedisTemplate is JdkSerializationRedisSerializer.
- RedisTemplate can store objects. When your data is a complex object type and you don't want to do any data conversion when taking it out, you can directly take an object out of Redis, so using RedisTemplate is a better choice.
4.2 common operations of RedisTemplate
redisTemplate.opsForValue(); //Operation string redisTemplate.opsForHash(); //Operation hash redisTemplate.opsForList(); //Operation list redisTemplate.opsForSet(); //Operation set redisTemplate.opsForZSet(); //Operation order set
4.3 use of RedisTemplate
Inject redisTemplate with @ Autowired annotation.
package com.xiao; import com.xiao.entity.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.util.*; import java.util.concurrent.TimeUnit; //Start the springboot application @SpringBootTest(classes = RedisDay2Application.class) public class TestRedisTemplate { //Inject redistemplate key object value object = = > object serialization name value user() = = > name serialization object serialization result @Autowired private RedisTemplate redisTemplate; //opsForxxx Value String Set Zset hash @Test public void testRedisTemplate(){ /** * redisTemplate The serialization of key and value in the object is jdkSerializationRedisSerializer * key: String * value: object * Modify the default key serialization scheme: key stringredisserializer */ //Modify key serialization scheme String type sequence redisTemplate.setKeySerializer(new StringRedisSerializer()); //Modify hash key serialization scheme redisTemplate.setHashKeySerializer(new StringRedisSerializer()); User user = new User(); user.setId(UUID.randomUUID().toString()).setName("Xiao Zhao").setAge(23).setBir(new Date()); redisTemplate.opsForValue().set("user",user); //The redis setting object needs to be serialized User user1 = (User)redisTemplate.opsForValue().get("user"); System.out.println(user1); redisTemplate.opsForList().leftPush("list",user); redisTemplate.opsForSet().add("set",user); redisTemplate.opsForZSet().add("zset",user,10); redisTemplate.opsForHash().put("map","name",user); } }