码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot RedisCacheConfig自定义设置

时间:2020-05-07 20:14:30      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:ehcache   tor   ati   article   opcache   root   poj   功能   查询   

Spring的@EnableCaching注解

@EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。如果你使用了这个注解,那么你就不需要在XML文件中配置cache manager了。

当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。

如果你对缓存感兴趣并想了解更多,请阅读spring caching. 本文会帮助你了解如何使用@EnableCaching注解。

接下来的例子演示了@EnableCaching的用法。在代码中,我缓存了Book类找那个的方法。

代码

//Book.java
import org.springframework.cache.annotation.Cacheable;
public class Book {
    @Cacheable(value = { "sampleCache" })
    public String getBook(int id) {
        System.out.println("Method executed..");
        if (id == 1) {
            return "Book 1";
        } else {
            return "Book 2";
        }
    }
}

//CachingConfig.java
import java.util.Arrays;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CachingConfig {
    @Bean
    public Book book() {
        return new Book();
    }

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache")));
        return cacheManager;
    }
}

上面的java config和下面的xml配置文件是等效的:

<beans>
     <cache:annotation-driven/>
     <bean id="book" class="Book"/>
     <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
         <property name="caches">
             <set>
                 <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
                     <property name="name" value="sampleCache"/>
                 </bean>
             </set>
         </property>
     </bean>
 </beans>
//EnableCachingAnnotationExample.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class EnableCachingAnnotationExample {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
        ctx.register(CachingConfig.class);
        ctx.refresh();
        Book book = ctx.getBean(Book.class);        
        // calling getBook method first time.
        System.out.println(book.getBook(1));
        // calling getBook method second time. This time, method will not
        // execute.
        System.out.println(book.getBook(1));
        // calling getBook method third time with different value.
        System.out.println(book.getBook(2));
        ctx.close();
    }
}

会得到如下的输出

 
Method executed..
Book 1
Book 1
Method executed..
Book 2

 

___________________________________________________________________________________________________________________________________________________________________________

 
技术图片
@Configuration
public class RedisCacheConfig {

    @Bean
    public KeyGenerator simpleKeyGenerator() {
        return (o, method, objects) -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(o.getClass().getSimpleName());
            stringBuilder.append(".");
            stringBuilder.append(method.getName());
            stringBuilder.append("[");
            for (Object obj : objects) {
                stringBuilder.append(obj.toString());
            }
            stringBuilder.append("]");

            return stringBuilder.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
            RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
            this.getRedisCacheConfigurationWithTtl(600), // 默认策略,未配置的 key 会使用这个
            this.getRedisCacheConfigurationMap() // 指定 key 策略
        );
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put("UserInfoList", this.getRedisCacheConfigurationWithTtl(3000));
        redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000));

        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        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);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
            RedisSerializationContext
                .SerializationPair
                .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }
}
技术图片

 

 
分类: RedisSpringBoot
 
==================================================================================================================================================================
 

SpringBoot配置RedisTemplate和RedisCacheManager

 https://blog.csdn.net/eric520zenobia/article/details/103286011/


展开
import com.dxy.cache.pojo.Dept;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.net.UnknownHostException;

@Configuration
public class MyRedisConfig {


/**
* 往容器中添加RedisTemplate对象,设置序列化方式
* @param redisConnectionFactory
* @return
* @throws UnknownHostException
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(valueSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(valueSerializer());
template.afterPropertiesSet();
return template;
}

/**
* 往容器中添加RedisCacheManager容器,并设置序列化方式
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}

// private final CacheProperties cacheProperties;
//
// MyRedisConfig(CacheProperties cacheProperties) {
// this.cacheProperties = cacheProperties;
// }

/**
* 往容器中添加org.springframework.data.redis.cache.RedisCacheConfiguration 对象
* 目的是为了向默认的RedisCacheManager中设置属性,当然包括序列化
* 如果仅仅是为了设置序列化方式可以和上面的配置二选一
* 在RedisCacheManager内部使用org.springframework.data.redis.cache.RedisCacheConfiguration去保存相关配置信息
*/
// @Bean
// public org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration() {
// CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
// org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
// .defaultCacheConfig();
// config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
// .fromSerializer(valueSerializer()));
// if (redisProperties.getTimeToLive() != null) {
// config = config.entryTtl(redisProperties.getTimeToLive());
// }
// if (redisProperties.getKeyPrefix() != null) {
// config = config.prefixKeysWith(redisProperties.getKeyPrefix());
// }if (!redisProperties.isCacheNullValues()) {
// config = config.disableCachingNullValues();
// }
// if (!redisProperties.isUseKeyPrefix()) {
// config = config.disableKeyPrefix();
// }
// return config;
// }

/**
* 使用Jackson序列化器
* @return
*/
private RedisSerializer<Object> valueSerializer() {
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
/**
* 这一句必须要,作用是序列化时将对象全类名一起保存下来
* 设置之后的序列化结果如下:
* [
* "com.dxy.cache.pojo.Dept",
* {
* "pid": 1,
* "code": "11",
* "name": "财务部1"
* }
* ]
*
* 不设置的话,序列化结果如下,将无法反序列化
*
* {
* "pid": 1,
* "code": "11",
* "name": "财务部1"
* }
*/
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//因为上面那句代码已经被标记成作废,因此用下面这个方法代替,仅仅测试了一下,不知道是否完全正确
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
return serializer;
}


}
import com.dxy.cache.mapper.DeptMapper;
import com.dxy.cache.pojo.Dept;
import com.dxy.cache.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

@Service("deptService")
public class DeptServiceImpl implements DeptService {

@Autowired
private DeptMapper deptMapper;

/**
* @Cacheable 包含的属性
* cacheNames/value:缓存的名字
* key:支持SpEL表达式,#id=#a0=#p0=#root.args[0] 都是取出第一个参数的意思
* #result :可以取出返回值
* keyGenerator:key生成器,和key属性二选一
* cacheManager:缓存管理器,获取缓存的
* condition:条件,满足条件时才缓存,如#id>0
* unless:除非,当表达式为true时不缓存 ,如:#result == null
* sync:是否使用异步模式
*
* 缓存原理:
* 1、自动配置 CacheAutoConfiguration
* 2、所有的缓存配置类
* org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
* org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
* org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
* org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
* org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
* org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
* org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
* org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
* 3、默认情况下,上面的配置类那个生效
* 4、给容器中创建了一个CacheManager:ConcurrentMapCacheManager
* 5、上述CacheManager可以创建和获取ConcurrentMapCache类型的缓存组件,它的作用是将数据存到ConcurrentMap中
*
* 运行流程:
* 1、方法运行之前,去查询Cache(缓存组件),通过配置的cacheNames去查询,第一次会先创建该组件
* 2、去Cache中查询缓存,通过key,默认key是方法参数,使用SimpleKeyGenerator生成key
* SimpleKeyGenerator生成key的策略:
* 如果没有参数:key = new SimpleKey()
* 如果有一个参数:key = 参数的值
* 如果有多个参数:key = new SimpleKey(多个参数)
* 3、如果没有查询到缓存则调用目标方法
* 4、将目标方法的返回值保存到缓存中
*
*
* @param id
* @return
*/
@Cacheable(cacheNames="dept",key="#p0")
@Override
public Dept getDeptById(Long id) {
System.out.println("发起数据库请求");
return deptMapper.getDeptById(id);
}

@Override
public int addDept(Dept dept) {
return deptMapper.addDept(dept);
}

@Override
/**
* 更新缓存,在方法之后执行
*/
@CachePut(cacheNames="dept",key="#p0.pid")
public Dept updateDeptById(Dept dept) {
deptMapper.updateDeptById(dept);
return dept;
}

@Override
/**
* 删除缓存
* 默认在方法执行之后进行缓存删除
* 属性:
* allEntries=true 时表示删除cacheNames标识的缓存下的所有缓存,默认是false
* beforeInvocation=true 时表示在目标方法执行之前删除缓存,默认false
*/
@CacheEvict(cacheNames = "dept",key = "#p0")
public int delDept(Long id) {
return deptMapper.delDept(id);
}

@Override
/**
* 组合@Cacheable、@CachePut、@CacheEvict的一个全面的注解
*/
@Caching(
cacheable = {
@Cacheable(cacheNames = "dept",key="#code")
},
put = {
@CachePut(cacheNames = "dept",key="#result.pid"),
@CachePut(cacheNames = "dept",key="#result.name"),
}

// ,
// evict = {
// @CacheEvict(cacheNames = "dept",key="#code")
// }
)
public Dept getDeptByCode(String code) {
return deptMapper.getDeptByCode(code);
}

}
 
————————————————————————————————————————————————————————————————————————————————————————————————— 
原文链接:https://blog.csdn.net/eric520zenobia/article/details/103286011/

 
 

SpringBoot RedisCacheConfig自定义设置

标签:ehcache   tor   ati   article   opcache   root   poj   功能   查询   

原文地址:https://www.cnblogs.com/kelelipeng/p/12844987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!