在已经搭建好的Spring Boot和MyBatis系统中加入Redis,可以按照以下步骤进行:

  1. 添加Redis依赖

在pom.xml文件中添加Redis的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis连接信息

在application.properties或application.yml文件中配置Redis连接信息:

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
  1. 编写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();
    }

}
  1. 在业务代码中使用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的步骤

怎么在已经搭建好的springboot和mybatis系统中加入redis

原文地址: https://www.cveoy.top/t/topic/cuJe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录