Building a Spring Boot RestController to Search Redis
In this post we take a look at how to build a simple Spring Boot RestController to search through a Redis instance. Come check out how easy this is!
Join the DZone community and get the full member experience.
Join For FreeI’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 while this is a bare minimum to get started, it 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.
Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments