Spring boot統合redisおよびredis注釈開発

7020 ワード

Spring boot統合redis
 
ステップ1:pom依存のインポート


    org.springframework.boot
    spring-boot-starter-data-redis



    redis.clients
    jedis

ステップ2:redisはspring bootグローバルプロファイルアプリケーションに構成する.yml
spring:   redis:       database: 0       host: 192.168.147.144       port: 6379       password: 123456          jedis:           pool:               max-active: 100               max-idle: 3               max-wait: -1               min-idle: 0       timeout: 1000
ここでspring bootはredisを構成し、ssmよりredisを構成し、ここではredisの登録情報、jedis接続プールjedis pool、jedisConnectionfactoryを構成する.
手順3:RedisConfigヘルプクラスの作成
package com.practice.springboot3.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
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.RedisCacheConfiguration;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Giraffe Wld
 * @site www.grf.com
 * @company grf  
 * @create  2019-03-15 16:08
 * redis   
 */
@Configuration
/** @Configuration     @Component ,  @Configuration     @Component    。
 @Configuration     spring   xml     。 */
@EnableCaching//       
//  CachingConfigurerSupport,       KEY   。     。
public class RedisConfig {

    /** RedisTemplate  StringRedisTemplate   
     *      :
     *      1,                ,          redis   ,               
     *      2,              ,RedisTemplate    JdkSerializationRedisSerializer                       Redis   。
     *    StringRedisTemplate    StringRedisSerializer
     *      ( map   )
     *      3,RedisTemplate                 ,  redisTemplate           
     *         StringRedisTemplate         ,         ,           ,     stringRedisTemplate
     *
     * */

    /**
     *   key        +   +             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();
            }
        };
    }

    /**
     *     
     *          redis     ,                   ,        element   redis
     *
     * @param redisConnectionFactory      yml   ,    
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //  Spring   RedisCacheConfiguration ,       redis   ,                      
        //              ,   RedisCacheManager  builder.build()     cacheManager:
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  //         ,  config              
        config = config.entryTtl(Duration.ofMinutes(1))     //            ,    Duration  
                .disableCachingNullValues();     //      

        //             set  
        Set cacheNames = new HashSet<>();
        cacheNames.add("my-redis-cache1");
        cacheNames.add("my-redis-cache2");

        //               
        Map configMap = new HashMap<>();
        configMap.put("my-redis-cache1", config);
        configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(120)));

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)     //                cacheManager
                .initialCacheNames(cacheNames)  //           ,                  ,         
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }

    /**    ,          hibernate ,     hibernateTemplate     ,
     *         ,         ,    redisTemplate,redis          ,         redis    ,
     *                    template   redis    */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //  Jackson2JsonRedisSerializer         redis value (    JDK      )
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //  StringRedisSerializer         redis key 
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**    stringRedisTemplate  redis   , */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

手順4:注釈式開発redis使用キャッシュ
指定したメソッドに使用する注釈を追加
/**  redis     
     * @Cacheable       ,     redis,    
     * @CachePut       redis,               ,    
     * @CacheEvict       redis      
     *     allEntries :          ;beforeInvocation :           
     * */

    /** value   :  redis             ; condition:  redis       ,      ; key:       redis    key  */
    @Cacheable(value = "my-redis-cache1",key = "'book'+#book_id", condition = "#book_id > 0")
    Book selectByPrimaryKey(Integer book_id);

さあ、遊びに行こう!!!