spring-boot-starter-redis Learning Notes

Keywords: Redis Spring Jedis Java

Personal notes are for reference only.

1. spring data redis recommends jedis, which is the java client of redis.

<dependency>  
	    <groupId>org.springframework.boot</groupId><!-- Incidental introduction jedis Package -->  
	    <artifactId>spring-boot-starter-redis</artifactId>  
</dependency>


2,RedisConnectionFactory

spring data redis connect to redis to obtain effective RedisConnection through RedisConnection Factory. RedisConnection is responsible for establishing and processing and redis back-end communications. RedisConnection provides getNative connection to return the underlying connection used for communication.


3,RedisTemplate

spring data redis supports low-level connection to Redis through connector and high-level friendly template class RedisTemplate, which is based on low-level connection. RedisConnection receives or returns byte arrays that require its own processing of connections, such as closing connections, while RedisTemplate handles serialization and de-serialization, and manages connections. RedisTemplate provides operational views such as (Bound) Value Operations, (Bound) List Operations, (Bound) Set Operations, (Bound) ZSet Operations, (Bound) Hash Operations. RedisTemplate is thread-safe and can be used in multiple instances.

RedisTemplate chooses java-based serialization by default or can switch to other serialization methods, or sets enabled DefaultSerializer to false or serializer to null, then RedisTemplate uses raw byte arrays represent data. Other serialization methods include protocol buffer, JSON, and binary byte stream with recursion.

String RedisTemplate is the only subclass of RedisTemplate.

RedisTemplate defines by default two commonly used serialization classes

private RedisSerializer<?> defaultSerializer = newJdkSerializationRedisSerializer();

And private RedisSerializer < String > stringSerializer = new String RedisSerializer ();

4. Serialization

Before you configure serialization, use

redisTemplate.opsForValue().set(key, value);
The resulting key and value will be serialized numbers or symbols, such as

To solve this problem, you need to serialize key and value, if it's xml-configured

We can inject the official keySerializer,valueSerializer,hashKeySerializer directly, so we need to write the RedisCacheConfig configuration class ourselves if we use annotations.

Caching has several main classes to implement:

1. Cache Manager cache manager;

2. Specific operation implementation class;

3. CacheManager factory class (which can be injected using configuration file configuration or implemented by encoding);

4. Cache key production strategy (of course Spring has its own generation strategy, but when viewed on the Redis client, it is serialized key, which is messy to our naked eyes. Here we use the caching strategy first).

/**
 * Cache Management (Annotation)
 * @author Administrator
 */
@Configuration
@EnableCaching//The meaning of enabling caching
public class CacheConfig extends CachingConfigurerSupport{
    
    /**
     * Custom key. This can be avoided
     * This method will generate a unique key based on the value of the class name + method name + all parameters, even if the value attribute in @Cacheable is the same, the key will be different.
     */
   /* @Override
    public KeyGenerator keyGenerator() {
       System.out.println("RedisCacheConfig.keyGenerator()");
       returnnew KeyGenerator() {
           @Override
           public Object generate(Object o, Method method, Object... objects) {
              // This will generate a unique key of the class name, the method name
              //and all method parameters appended.
              StringBuilder sb = new StringBuilder();
              sb.append(o.getClass().getName());
              sb.append(method.getName());
              for (Object obj : objects) {
                  sb.append(obj.toString());
              }
              System.out.println("keyGenerator=" + sb.toString());
              returnsb.toString();
           }
       };
    }
    */
    
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
       /* //Setting cache expiration time
        // rcm.setDefaultExpiration(60);//second
        //Setting the expiration time of value
        Map<String,Long> map=new HashMap();
        map.put("test",60L);
        rcm.setExpires(map);*/
        return rcm;
    }
    /**
     * RedisTemplate To configure
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        //Define key serialization
        //RedisSerializer < String > redisSerializer = new String RedisSerializer (); //Long type will appear exception information; need our custom key generation strategy above, generally not necessary
        //Define the serialization of value
        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);
        
       // template.setKeySerializer(redisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

Posted by reinaldo on Fri, 14 Jun 2019 17:52:54 -0700