1. Integration steps
1.1 introduction of springdataredis starter
<!-- Spring Data Redis Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
1.2 write the configuration class of Spring Data Redis
Steps:
1) Create a JedisPoolConfig object. Complete some link pool configuration in this object
2) Create JedisConnectionFactory: configure redis link information
3) Create RedisTemplate: method used to perform Redis operation
The configuration classes are as follows:
package com.bjc.conf; 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.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; /**redis Configuration class * @Configuration Used to identify the class as a configuration class * */ @Configuration public class Redisconfg { /** * 1.Create a JedisPoolConfig object. Complete some link pool configuration in this object * @Bean Annotation is used to initialize the code of loading @ Bean annotation when loading @ Configuration at boot time */ @Bean public JedisPoolConfig JedisPoolConfig() { // 1. Create connection pool object JedisPoolConfig pool = new JedisPoolConfig(); // 2. Optional configuration pool.setMaxIdle(10); //Maximum number of idle pool.setMinIdle(5); //Minimum number of idle pool.setMaxTotal(20); //Maximum number of links return pool; } /** * 2.Create JedisConnectionFactory: configure redis link information */ @Bean public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config) { // 2.1 creating a JedisConnectionFactory factory factory object JedisConnectionFactory factory = new JedisConnectionFactory(); // 2.2 setting RedisPool connection pool factory.setPoolConfig(config); // 2.3 setting connection information factory.setHostName("localhost"); factory.setPort(6379); // Specify the redis database. Redis has 16 databases by default, which points to index database 0 by default // factory.setDatabase(1); return factory; } /** * 3.Create RedisTemplate: method used to perform Redis operation */ public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory) { // 3.1 create template object and set connection factory RedisTemplate<String,Object> template = new RedisTemplate<String,Object>(); template.setConnectionFactory(factory); // 3.2 set serializer //Set serializer for key template.setKeySerializer(new StringRedisSerializer()); //Set serializer for value template.setValueSerializer(new StringRedisSerializer()); return template; } }
1.3 simple test
package com.bjc.test; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class RedisTest { @Resource private RedisTemplate<String,Object> templete; @Test public void test01() { templete.boundValueOps("name").set("Zhang San"); } @Test public void test02() { String value = (String) templete.boundValueOps("name").get(); System.out.println(value); } }
View the redis tool. You can see that the stored key is name and the value is Zhang San
The result of program running is also the output of Zhang San
Note: in addition to the boundValueOps, the api for operating redis also has an opsForValue, for example:
@Test public void test03() { templete.opsForValue().set("age", "21"); } @Test public void test04() { String age = (String) templete.opsForValue().get("age"); System.out.println(age); }
2. Extract the link parameters of Redis
2.1 extract configuration information
We put some link information of redis in the configuration class. Once the environment changes, it is inconvenient to change the code. Therefore, we can put these configuration information in the configuration file and add the following link information in the application.properties file:
spring.redis.pool.max-idle=10 spring.redis.pool.min-idle=5 spring.redis.pool.max-total=20 spring.redis.hostName=localhost spring.redis.port=6379
Note: the prefix is customized, but the suffix is fixed. For example: spring. Redis. Pool. Max idle = 10 can be written as AAA. BBB. CCC. Max idle = 10, where Max idle is fixed.
2.2 read configuration information - @ ConfigurationProperties
We have configured the link information in the configuration file, so how can we introduce this information into our configuration class? spring provides an annotation @ ConfigurationProperties, which can extract the part with the same prefix in the configuration file, create a real body, and then show the suffix as the property of an entity. The prefix content is specified by the attribute prefix. In this way, we don't need to specify parameter information in the configuration class. We just need to create and return, and boot will automatically inject parameters into the object.
For example: modification of reading connection pool configuration information from configuration file
/** * 1.Create a JedisPoolConfig object. Complete some link pool configuration in this object * @Bean Annotation is used to initialize the code of loading @ Bean annotation when loading @ Configuration at boot time */ @Bean @ConfigurationProperties(prefix = "spring.redis.pool") public JedisPoolConfig JedisPoolConfig() { // 1. Create connection pool object JedisPoolConfig pool = new JedisPoolConfig(); /** Changed to extract parameters from the configuration file, no need to specify here // 2. Optional configuration pool.setMaxIdle(10); //Maximum number of idle pool.setMinIdle(5); //Minimum number of idle pool.setMaxTotal(20); //Maximum number of links */ return pool; }
Change the Jedis connection factory configuration information to read from the configuration file
/** * 2.Create JedisConnectionFactory: configure redis link information */ @Bean @ConfigurationProperties(prefix = "spring.redis") public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config) { // 2.1 creating a JedisConnectionFactory factory factory object JedisConnectionFactory factory = new JedisConnectionFactory(); // 2.2 setting RedisPool connection pool factory.setPoolConfig(config); // 2.3 setting connection information // factory.setHostName("localhost"); // factory.setPort(6379); // Specify the redis database. Redis has 16 databases by default, which points to index database 0 by default // factory.setDatabase(1); return factory; }
Test again, found that the program can run normally, indicating that the configuration has taken effect!
3. Access Java objects
The previous examples are all about string manipulation. Now let's see how to use SpringDataRedis to manipulate java objects.
3.1 save object
Create a new entity class user, directly set the user object to redis, and the program reports an error. This is because we set the serializer of value in the configuration object as string serializer. springdateRedis can't convert the object to string type, so the type conversion exception is reported. At the same time, we know that a serializable jar is provided in the spring dataredis core package, There are many serializers, as shown in the figure:
You can see the fifth serializer, JdkSerializationRedisSerializer.class. We can specify the current serializer as JdkSerializationRedisSerializer. For example:
@Test public void test05() { // Reset serializer templete.setValueSerializer(new JdkSerializationRedisSerializer()); templete.opsForValue().set("user", new User("Zhang San",23,new Date())); }
Viewing redis, you can see the stored information, as shown in the figure:
Note: entity classes need to implement the serialization interface
3.2 taking objects
We can't call the get method directly to get the object information. We also need to re specify the serializer before getting it
For example:
@Test public void test06() { // Reset serializer templete.setValueSerializer(new JdkSerializationRedisSerializer()); User user = (User) templete.opsForValue().get("user"); System.out.println(user); }
Output results:
Note: the same effect can be achieved through boundValueOps. You also need to specify a serializer, for example;
@Test public void test05() { // Reset serializer templete.setValueSerializer(new JdkSerializationRedisSerializer()); templete.boundValueOps("users").set(new User("Zhang San",23,new Date())); } @Test public void test06() { // Reset serializer templete.setValueSerializer(new JdkSerializationRedisSerializer()); User user = (User) templete.boundValueOps("users").get(); System.out.println(user); }
4. Access entity objects in JSON format
Previously, we realized the access to the object through the serializer of jdk. However, there is an obvious defect in this way, that is, the storage space is relatively large. Compared with the JSON format, the storage way of serializing bytecode is very heavy. So, next, we will introduce how to use the JSON format to store the object.
4.1 deposits
Let's take a look at the serialization jar of the core jar of SpringDataRedis. We find that there are three serializers that can operate json: GenericJackson2JsonRedisSerializer, Jackson2JsonRedisSerializer, and JacksonJsonRedisSerializer, as shown in the figure:
We found that Jackson JSON redisserializer is an obsolete class, so we can use two other serializers
For example:
@Test public void test07() { // Reset serializer templete.setValueSerializer(new Jackson2JsonRedisSerializer<User>(User.class)); templete.boundValueOps("jsonUser").set(new User("Zhang San",23,new Date())); }
Execute the program, check the redis management client, as shown in the figure, and find that the stored objects are stored in json format
4.2 take
The method of fetching is also very simple. You need to specify the corresponding serializer, for example;
@Test public void test08() { // Reset serializer templete.setValueSerializer(new Jackson2JsonRedisSerializer<User>(User.class)); User user = (User) templete.boundValueOps("jsonUser").get(); System.out.println(user); }