springboot集成redis

本文详细介绍如何在Spring Boot项目中整合Redis,包括配置Maven依赖、设置Redis基本信息、创建RedisConfig类、添加@EnableCaching注解及实现缓存CRUD同步的方法。通过具体示例帮助开发者快速掌握使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入maven依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.设置redis基本信息

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database = 8 
spring.redis.timeout=5000
spring.redis.defaultExpireTime=7200
spring.redis.pool.max-active=50
spring.redis.pool.max-idle=20
spring.redis.pool.min-idle=10
spring.redis.pool.max-wait=10000

3.创建RedisConfig类

@Configuration
@ConfigurationProperties(prefix = "spring.redis")
@Getter
@Setter
public class RedisConfig {

	private int defaultExpireTime;
	
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
    	Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
				Object.class);
		ObjectMapper om = new ObjectMapper();
		om.findAndRegisterModules();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
				.entryTtl(Duration.ofSeconds(defaultExpireTime));
		config.serializeValuesWith(
				RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
		RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).transactionAware()
				.build();
		return cacheManager;
    }
}

4.springboot启动类添加@EnableCaching注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@EnableCaching
public class ChilddreamServiceApplication {
	public static void main(String[] args) {
		SpringApplication.run(ChilddreamServiceApplication.class, args);
	}
}

5.改造service中crud方法,实现缓存crud同步,
保存方法:

	@CachePut(cacheNames="subject", key = "'SubjectBaseInfo.'+#subject.id")
	@Transactional(rollbackFor = Exception.class)
	public Subject save(Subject subject) {
		Assert.notNull(subject, "科目信息不能为空!");
		return this.subjectRespository.save(subject);
	}

查询方法:

	@Cacheable(cacheNames="subject", key = "'SubjectBaseInfo.'+#id")
	public Subject findById(Long id) {
		Assert.notNull(id, "科目id不能为空!");
		return this.subjectRespository.findByIdAndStatus(id, true);
	}

下面链接是缓冲注解详细讲解链接:
讲解链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值