Building a Spring Boot RestController to search Redis

I’ve just started taking a look at using Redis. I wondered what it would look like to build a simple REST interface with Spring Boot. Spring Data Redis makes this pretty simple.

First up, you need to configure a @Bean in your @SpringBootApplication class (full source is on github here):

@Bean
RedisTemplate<String, Object> redisTemplate() {
  RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
  template.setConnectionFactory(jedisConnectionFactory());

  // these are required to ensure keys and values are correctly serialized
  template.setKeySerializer(new StringRedisSerializer());
  template.setHashValueSerializer(new GenericToStringSerializer<Object>(Object.class));
  template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
  return template;
}

This is connecting with default settings to a locally running Redis.

Wire up a RedisTemplate into a Controller like this:

@RestController
public class RedisRestController {

  @Autowired
  private RedisTemplate<String, Object> template;

  @GetMapping("singlekey/{key}")
  public RedisResult getSingleValue(@PathVariable("key") String key){
    String value = (String)this.template.opsForValue().get(key);
    RedisResult result = new RedisResult(key, value);
    return result;
  }
}

and this is a bare minimum to get started, but shows how easy it is to get stuff up and running with Spring Boot and other projects like Spring Data.

Send a GET to /singlekey/ with a key value and json for the result is returned.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.