Springと連携させ、Redisを使う方法
RedisをSpringで利用するには、次の手順で実装できます。
- pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- application.properties
- application.yml
spring.redis.host=localhost
spring.redis.port=6379
- 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;
}
}
- RedisTemplate
- 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のデータを操作できます。