springboot cache + redis RedisConfig配置文件

package com.springboot.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.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;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

	// 自定义缓存key生成策略
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
				StringBuffer sb = new StringBuffer();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}

	// 缓存管理器
	@Bean
	public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
		RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
		// 设置缓存过期时间
		cacheManager.setDefaultExpiration(10000);
		return cacheManager;
	}

	@Bean
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		StringRedisTemplate template = new StringRedisTemplate(factory);
		setSerializer(template);// 设置序列化工具
		template.afterPropertiesSet();
		return template;
	}

	private void setSerializer(StringRedisTemplate template) {
		@SuppressWarnings({ "rawtypes", "unchecked" })
		Jackson2JsonRedisSerializer 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);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用SpringBoot结合Redis实现缓存功能的步骤如下: 1. 在pom.xml文件中添加Redis依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息,在application.properties文件中添加以下配置: ``` # Redis连接信息 spring.redis.host=<redis服务器IP> spring.redis.port=<redis服务器端口> spring.redis.password=<redis密码> ``` 3. 创建一个Redis配置类,用于将RedisTemplate注入到Spring容器中: ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 4. 编写Cacheable注解,用于对需要缓存的方法进行标注: ``` @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Cacheable { // 缓存key的前缀 String prefix() default ""; // 缓存时间,默认为30分钟 long expireTime() default 1800L; } ``` 5. 编写缓存切面,对被Cacheable注解标注的方法进行缓存: ``` @Aspect @Component public class CacheAspect { @Autowired private RedisTemplate<String, Object> redisTemplate; @Around("@annotation(com.example.demo.annotation.Cacheable)") public Object cache(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法参数 Object[] args = joinPoint.getArgs(); // 获取方法名 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); String methodName = method.getName(); // 获取注解信息 Cacheable cacheable = method.getAnnotation(Cacheable.class); String prefix = cacheable.prefix(); long expireTime = cacheable.expireTime(); // 构造缓存key StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(prefix); for (Object arg : args) { keyBuilder.append(":").append(arg); } String key = keyBuilder.toString(); // 从缓存中获取数据 Object value = redisTemplate.opsForValue().get(key); if (value != null) { return value; } // 缓存中不存在则调用方法,将返回值存入缓存 Object result = joinPoint.proceed(args); redisTemplate.opsForValue().set(key, result, expireTime, TimeUnit.SECONDS); return result; } } ``` 6. 在需要进行缓存的方法上加上Cacheable注解,即可实现缓存功能: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Cacheable(prefix = "user", expireTime = 3600L) public User getUserById(Integer id) { return userDao.getUserById(id); } } ``` 这样,在调用getUserById方法时,如果缓存中已经存在数据,则直接返回缓存中的数据;否则调用方法,将返回值存入缓存,并返回结果。这样可以有效地减少数据库的访问次数,提高系统的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值