Springboot 使用Redis註解

Springboot 使用Redis註解

配置yml

spring:
  cache:
    cache-names: mdc-cache
  redis:
    host: ${spring.redis.host}
    password: ${spring.redis.password}
    port: ${spring.redis.port}
    timeout: ${spring.redis.timeout}

RedisConfiguration配置

package com.paascloud.provider.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.CachingConfigurerSupport;
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.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;

/**
 * The class Redis configuration.
 * Created by [email protected]
 */
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * Key generator key generator.
     *
     * @return the key generator
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, 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();
        };

    }

    /**
     * Cache manager cache manager.
     *
     * @param redisTemplate the redis template
     *
     * @return the cache manager
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    /**
     * Redis template redis template.
     *
     * @param factory the factory
     *
     * @return the redis template
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer<Object> 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.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

web層

    @PostMapping(value = "/get4City")
    @ApiOperation(httpMethod = "POST", value = "查看四級地址")
    public Wrapper<List<TreeNode>> get4City() {
        logger.info("get4City - 獲取四級地址");
        List<TreeNode> treeNodeList = mdcAddressService.get4City();
        return WrapMapper.ok(treeNodeList);
    }

serviceImpl

@Override
    @Cacheable(cacheNames="mdc-cache")
    public List<TreeNode> get4City() {
        List<MdcAddress> mdcAddresses = mdcAddressMapper.selectAll();
        List<TreeNode> treeNodeList = buildGroupTree(mdcAddresses);
        logger.info("treeNodeList={}", treeNodeList);
        return treeNodeList;
    }

小坑

java.lang.ClassCastException: org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String

解決辦法

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport  {
  @Bean
  @Override
  public KeyGenerator keyGenerator() { ... }

  ...
}

參考
http://blog.csdn.net/a67474506/article/details/52608855

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