Redis設定用ラクラス


import java.time.Duration;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {

@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.database}")
private int redisDb;
@Value("${spring.redis.timeout}")
private int redisTimeout;

/**
* Redisテンプレートオブジェクトを取得する.
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, ?> getRedisTemplate(RedisConnectionFactory factory) {

RedisStandaloneConfiguration redisStandaloneConfiguration =
new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setDatabase(redisDb);
redisStandaloneConfiguration.setHostName(redisHost);
redisStandaloneConfiguration.setPort(redisPort);
GenericObjectPoolConfig<?> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
lettucePoolingClientConfigurationBuilder = LettucePoolingClientConfiguration.builder();
lettucePoolingClientConfigurationBuilder.poolConfig(genericObjectPoolConfig);
if (redisTimeout > 0) {
lettucePoolingClientConfigurationBuilder.commandTimeout(Duration.ofMillis(redisTimeout));
}
LettuceConnectionFactory connectionFactory =
new LettuceConnectionFactory(redisStandaloneConfiguration,
lettucePoolingClientConfigurationBuilder.build());
connectionFactory.afterPropertiesSet();

RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer jsonRedisSerializer
= new GenericJackson2JsonRedisSerializer();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setDefaultSerializer(jsonRedisSerializer);
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(jsonRedisSerializer);
redisTemplate.setHashValueSerializer(jsonRedisSerializer);
redisTemplate.afterPropertiesSet();

return redisTemplate;
}
}

posted @ 2020-09-02 16:42  dunkbird  阅读(118)  评论(0编辑  收藏  举报