SpringDataRedisを使ってJson形式でオブジェクトをRedisに保存する方法
SpringDataRedisを使ってObjectを保存するとデフォルト設定ではKey、Value共に可読性の悪いserializeされたデータになります
テストや運用の効率を考慮して可読性の高いJson形式でデータを保存したくなったので方法を記録しておきます。
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <!-- Json に変換するために必要 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
Configクラス
@Configuration @ComponentScan(basePackages="redisSample") @EnableWebMvc public class WebApplicationConfig extends WebMvcConfigurerAdapter { @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory cf = new JedisConnectionFactory(); cf.setUsePool(true); cf.setHostName("localhost"); cf.setPort(6379); return cf; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> rt = new RedisTemplate<String, Object>(); rt.setConnectionFactory(jedisConnectionFactory()); // key のSerialize方法を指定 rt.setKeySerializer(new StringRedisSerializer()); // Value のSerialize方法を指定 rt.setValueSerializer(new JacksonJsonRedisSerializer<>(Object.class)); return rt; } }
コントローラー
オブジェクトを出したり入れたりする
@RestController @EnableWebMvc public class SampleController { @Autowired RedisTemplate<String, Object> redisTemplate; @RequestMapping(value = "/getData", method = RequestMethod.GET) public void getData(@RequestParam("key") String key, HttpServletResponse res) throws IOException { res.getWriter().write(redisTemplate.opsForValue().get(key).toString()); } @RequestMapping(value = "/setData", method = RequestMethod.GET) public void setData(@RequestParam("key") String key,@RequestParam("value") String value, HttpServletResponse res) throws IOException { SampleDto dto = new SampleDto(); dto.value = value; dto.creationDateTime = System.currentTimeMillis(); redisTemplate.opsForValue().set(key, dto); res.getWriter().write("OK"); } }
保存するオブジェクト
public class SampleDto { public String value; public long creationDateTime; }
確認
起動
java -jar target/redisSample-0.0.1-SNAPSHOT.jar
set
wget "http://localhost:8080/setData?value=hoge&key=key1"
get
wget "http://localhost:8080/getData?key=key1" cat getData\?key\=key1 # {value=hoge, creationDateTime=1440077026083}
redis
get key1 # "{\"value\":\"hoge\",\"creationDateTime\":1440077026083}"