springboot整合redis时,使用@Cacheable注解,如果方法的key参数为空,就会报org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String的错误。
org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String
package com.test.config; 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.core.RedisTemplate; /** * Created by toutou on 2019/3/9. */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Override @Bean 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(); }; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // 设置默认过期时间为60秒 cacheManager.setDefaultExpiration(60); return cacheManager; } }