Spring Boot 和 MyBatis 系统集成 Redis 缓存 - 详细步骤指南
在已经搭建好的 Spring Boot 和 MyBatis 系统中加入 Redis,可以按照以下步骤进行:
- 添加 Redis 依赖
在 pom.xml 文件中添加 Redis 的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置 Redis 连接信息
在 application.properties 或 application.yml 文件中配置 Redis 连接信息:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
- 编写 Redis 配置类
编写一个 Redis 配置类,用于配置 Redis 连接池和 RedisTemplate 等信息:
@Configuration
public class RedisConfig {
@Bean
public JedisPool jedisPool() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(100);
poolConfig.setMaxIdle(50);
poolConfig.setMinIdle(10);
poolConfig.setMaxWaitMillis(5000);
return new JedisPool(poolConfig, 'localhost', 6379);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.transactionAware()
.build();
}
}
- 在业务代码中使用 Redis
通过注入 RedisTemplate 对象,即可在业务代码中使用 Redis,例如:
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void saveToRedis(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getFromRedis(String key) {
return redisTemplate.opsForValue().get(key);
}
以上就是在已经搭建好的 Spring Boot 和 MyBatis 系统中加入 Redis 的步骤。
原文地址: https://www.cveoy.top/t/topic/nv8S 著作权归作者所有。请勿转载和采集!