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

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}