pom.xml
添加 org.springframework.boot:spring-boot-starter-data-redis
,org.apache.commons:commons-pool2
两个依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
bootstrap.yml
spring:
application:
name: itoken-service-redis
redis:
lettuce:
pool:
max-active: 8
max-idle: 8
max-wait: -1ms
min-idle: 0
sentinel:
master: mymaster
nodes: 192.168.106.140:26379
server:
port: 8502
RedisServcie
package com.yuu.itoken.service.redis.service;
public interface RedisService {
public void set(String key, Object value, long seconds);
public Object get(String key);
}
RedisServiceImpl
package com.yuu.itoken.service.redis.service.impl;
import com.yuu.itoken.service.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate redisTemplate;
@Override
public void set(String key, Object value, long seconds) {
redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}
@Override
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
}
RedisController
package com.yuu.itoken.service.redis.controller;
import com.yuu.itoken.service.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RedisController {
private static final String RESULT_OK = "ok";
@Autowired
private RedisService redisService;
@RequestMapping(value = "put", method = RequestMethod.GET)
public String set(String key, String value, long seconds) {
redisService.set(key, value, seconds);
return RESULT_OK;
}
@RequestMapping(value = "find", method = RequestMethod.GET)
public String find(String key) {
String json = null;
Object obj = redisService.get(key);
if (obj != null) {
json = (String) redisService.get(key);
}
return json;
}
}