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<String, String> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, String> template = new RedisTemplate<>();

        RedisSerializer<String> 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<AccountInfo> 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

key

value存儲在 test_redis~keys中相對應的key

  • test_aa 爲我們設置的redis key

value


代碼

代碼請移步 Github參考地址

如有疑問請加公衆號(K171),如果覺得對您有幫助請 github start
公衆號_k171

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章