Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Building a Spring Boot RestController to Search Redis

DZone's Guide to

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!

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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 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.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
redis ,spring boot ,restcontroller ,java ,tutorial

Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}