大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
Springboot 集成Redis
添加Redis依赖
<depency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
配置文件:
spring:
redis:
timeout: 0
#Redis服务器地址
host: 127.0.0.1
#Redis服务器连接端口
port: 6379
#Redis服务器连接密码(默认为空)
password:
cache:
redis:
time-to-live: 60000
自定义RedisTemplate
@Bean
@Primary
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
template.setDefaultSerializer(genericJackson2JsonRedisSerializer());
return template;
}
private RedisSerializer<Object> genericJackson2JsonRedisSerializer() {
return new GenericJackson2JsonRedisSerializer(buildMapper());
}
private ObjectMapper buildMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//设置类型
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.PROPERTY);
//支持java8 时间序列化
objectMapper.registerModule(new JavaTimeModule());
//忽略null值
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
后续使用RedisTemplate<String,Object>操作缓存;
使用注解进行缓存操作涉及CacheManage
RedisCacheManager源码
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisConnectionFactory.class)
@AutoConfigureAfter(RedisAutoConfiguration.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnMissingBean(CacheManager.class)
@Conditional(CacheCondition.class)
class RedisCacheConfiguration {
@Bean
RedisCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers cacheManagerCustomizers,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) {
RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(
determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader()));
List<String> cacheNames = cacheProperties.getCacheNames();
if (!cacheNames.isEmpty()) {
builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
}
redisCacheManagerBuilderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return cacheManagerCustomizers.customize(builder.build());
}
}
RedisCacheConfiguration 会注入一个RedisCacheManager ,内部使用JDK序列化;如果想使用自己定义的序列化方式,可以提供一个RedisCacheConfiguration bean,或者实现RedisCacheManagerBuilderCustomizer接口,对RedisCacheManagerBuilder进行更改;
提供RedisCacheConfiguration bean
@Bean
public RedisCacheConfiguration determineConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 设置redis中值的序列化方式,方便redisClient可读
config = config.serializeValuesWith(SerializationPair.fromSerializer(jackson2JsonRedisSerializer())).computePrefixWith(name -> name + ":");//替换掉默认的双冒号
Redis redisProperties = cacheProperties.getRedis();
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
/** * 使用Jackson序列化器 */
private RedisSerializer<Object> jackson2JsonRedisSerializer() {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
jackson2JsonRedisSerializer.setObjectMapper(buildMapper());
return jackson2JsonRedisSerializer;
}
private ObjectMapper buildMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//设置类型
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.PROPERTY);
Set<Object> registeredModuleIds = objectMapper.getRegisteredModuleIds();
registeredModuleIds.forEach(System.out::println);
objectMapper.registerModule(new JavaTimeModule());
//忽略null值
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
spring-boot-starter-data-redis 会使用RedisAutoConfiguration自动配置:
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
//属性配置
@EnableConfigurationProperties(RedisProperties.class)
//连接配置
@Import({
LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration{
......
}
2.x版本默认使用lettuce作为客户端;
连接池pool虽然有默认值,但是并不会启用
/** * Pool properties. */
public static class Pool {
/** * Maximum number of "idle" connections in the pool. Use a negative value to * indicate an unlimited number of idle connections. */
private int maxIdle = 8;
/** * Target for the minimum number of idle connections to maintain in the pool. This * setting only has an effect if both it and time between eviction runs are * positive. */
private int minIdle = 0;
@Bean
@ConditionalOnMissingBean(RedisConnectionFactory.class)
LettuceConnectionFactory redisConnectionFactory(
ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
ClientResources clientResources) throws UnknownHostException {
//这里的getPool会是null,需要在yml设置一个pool属性才会创建pool对象
LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(builderCustomizers, clientResources,
getProperties().getLettuce().getPool());
return createLettuceConnectionFactory(clientConfig);
}
springboot注解操作缓存
注解 | 使用方式 |
---|---|
@CacheConfig | 作用在类上的配置型注解,cacheNames 设置key前缀, 默认会用::与后面的key拼接,cacheManger 指定缓存使用的cacheManger |
@Cacheable | 作用在方法上,先获取缓存,缓存没有就执行方法,将方法的返回值缓存起来,eg: @Cacheable(key = “#p0.id”, condition = “#p0.id!=null”) EL表达式参考源码注释 |
@CachePut | 添加缓存:会替换掉现有的缓存 ;eg:@CachePut(key = “#result.id”, unless = “#result==null”) |
@CacheEvict | 缓存删除, 可以指定删除指定的key,也可以删除全部, 删除缓存的操作默认在方法执行后,通过beforeInvocation设置 |
所有的注解操作都会涉及CacheManger, 在上下文只有一个CacheManger时会默认使用,否则需要在注解中指明.
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/190724.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...