Springboot整合Cache缓存组件(Redis,Caffine,Jetcache,EhCache等)

Springboot整合缓存组件

主要包括:

  • springboot-cache以及注解使用
  • springboot-data-redis分布式缓存–【这里省略会有专题介绍】
  • caffine 内存缓存插件
  • jetcache2 双缓存插件
  • memcached 缓存插件
  • ehcache 缓存插件

一、spring-boot-cache快速入门

1、添加依赖
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-cacheartifactId>
dependency>
2、添加配置项
spring:
  cache:
    type: caffeine  # 这里可以改成redis,jetcache
    cache-names:
    - getPersonById  # 指定缓存名称
    - name2
    caffeine:
      spec: maximumSize=500,expireAfterWrite=5s   # 缓存配置


3、添加各种方式的注解
//使用Redis作为缓存
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
   
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Autowired
    private Environment env;

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
   
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
        redisConnectionFactory.setHostName(env.getProperty("redis.hostname"));
        redisConnectionFactory.setPort(Integer.parseInt(env.getProperty("redis.port")));
        return redisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
   
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(cf);
        return redisTemplate;
    }
    // 将RedisCacheManager注入到CacheManager
    @Bean
    public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
   
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(600);
        return cacheManager;
    }
	@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();
            }

        };
    }
    public CacheErrorHandler errorHandler() {
   
        return new CacheErrorHandler(){
   
            @Override
            public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
   
                logger.warn("handleCacheGetError in redis: {}", exception.getMessage());
            }
            @Override
            public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
   
                logger.warn("handleCachePutError in redis: {}", exception.getMessage());
            }
            @Override
            public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
   
                logger.warn("handleCacheEvictError in redis: {}", exception.getMessage());
            }
            @Override
            public void handleCacheClearError(RuntimeException exception, Cache cache) {
   
                logger.warn("handleCacheClearError in redis: {}", exception.getMessage());
            }};
    }
}
//使用GuavaCache缓存
@Configuration
public class GuavaCacheConfig {
   
    @Bean
    public CacheManager getCacheManager() {
   
        GuavaCacheManager cacheManager =

你可能感兴趣的:(Springboot项目基础,缓存,redis,spring,boot)