Quantcast
Channel: CodeSection,代码区,数据库(综合) - CodeSec
Viewing all articles
Browse latest Browse all 6262

Building a Spring Boot RestController to Search Redis

$
0
0

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.


Viewing all articles
Browse latest Browse all 6262

Trending Articles