Springと連携させ、Redisを使う方法

RedisをSpringで利用するには、次の手順で実装できます。

  1. pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. application.properties
  2. application.yml
spring.redis.host=localhost
spring.redis.port=6379
  1. Redisテンプレート
@Configuration
public class RedisConfig {

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName("localhost");
        configuration.setPort(6379);
        return new JedisConnectionFactory(configuration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }
}
  1. RedisTemplate
  2. Redisテンプレート
@Service
public class ExampleService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void saveData(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getData(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

上記の手順により、SpringでRedisを使用できるようになります。要件に合わせてRedisTemplateメソッドを使用してRedisのデータを操作できます。

bannerAds