SpringBoot -- 集成Redis/CacheManager

前置工作

  • 了解Redis、Cache
  • spring-data-redis

Demo

引入 spring-data-redis

build.gradle

compile ('org.springframework.data:spring-data-redis')
compile ('redis.clients:jedis')

创建 RedisConfig,与Spring Cache进行集成;

  • 与Spring Cache进行集成时需要key、value的 序列化,不然会出现 \xAC\xED\x00\x05t\x00\x06之类的
  • 与Spring Cache集成后redis key会存入 cachekey+~keys中 xxx~keys

RedisConfig.java

/**
 * @author cwenao
 * @version $Id RedisConfig.java, v 0.1 2017-01-29 15:17 cwenao Exp $$
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Bean(name="redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate template = new RedisTemplate<>();

        RedisSerializer redisSerializer = new StringRedisSerializer();

        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }

    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate) {

        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(3000);
        return cacheManager;
    }

}

配置 redis连接信息,redis启用了密钥

application.yml

Spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 111222333444555666
    timeout: 5000
    pool:
      max-idle: 8
      min-idle: 0
      max-active: 8
      max-wait: -1

创建 Cache 操作类

/**
 * @author cwenao
 * @version $Id AbstractCacheSupport.java, v 0.1 2017-01-29 15:35 cwenao Exp $$
 */
public abstract class AbstractCacheSupport {

    /**
     * 获取缓存内容
     * @param cache
     * @param key
     * @return
     */
    protected Object getFromCache(Cache cache, String key) {
        final Cache.ValueWrapper valueWrapper = cache.get(key);
        return null == valueWrapper ? null : valueWrapper.get();
    }

    /**
     * 设置缓存数据
     * @param cache
     * @param key
     * @param value
     * @return
     */
    protected boolean putCache(Cache cache, String key, Object value) {
        if (null == value) {
            return false;
        }
        cache.put(key, value);

        return true;
    }

    /**
     * 删除缓存数据
     * @param cache
     * @param key
     * @return
     */
    protected boolean evictFromCache(Cache cache,Object key){
        if(null == key){
            return false;
        }
        cache.evict(key);

        return true;
    }
}

创建 Controller 类此处用 集成Mybatis时的controller

  • 加入缓存key private final static String TEST_REDIS = “test_redis”
  • 设置key-value :
    Cache cache = cacheManager.getCache(TEST_REDIS);
    putCache(cache,”test_aa”,”111111”);
/**
 * @author cwenao
 * @version $Id UserInfoController.java, v 0.1 2017-01-25 18:35 cwenao Exp $$
 */
@Controller
public class UserInfoController extends AbstractCacheSupport {

    @Autowired
    AccountInfoServer accountInfoServerImpl;

    @Autowired
    CacheManager cacheManager;

    private final static String TEST_REDIS = "test_redis";

    @RequestMapping("/accountInfo")
    public String accountInfo(String name, ModelMap modelMap) {
        Cache cache = cacheManager.getCache(TEST_REDIS);
        putCache(cache,"test_aa","111111");
        List accountInfoList = accountInfoServerImpl.selectByName(name);
        modelMap.addAttribute("accountList", accountInfoList);
        System.out.println(getFromCache(cache,"test_aa"));
        return "userinfo/accountInfo";

    }
}

测试

访问 http://localhost:10002/dbserver/accountInfo?name=cwenao

Key 存储在 test_redis~keys中

  • test_redis~keystest_redis为 Cache的key

SpringBoot -- 集成Redis/CacheManager_第1张图片

value存储在 test_redis~keys中相对应的key

  • test_aa 为我们设置的redis key

SpringBoot -- 集成Redis/CacheManager_第2张图片


代码

代码请移步 Github参考地址

如有疑问请加公众号(K171),如果觉得对您有帮助请 github start
SpringBoot -- 集成Redis/CacheManager_第3张图片

你可能感兴趣的:(spring,boot/spring,cloud)