Spring boot 基于Spring, Redis集成与Spring大同小异。
文章示例代码均以前篇笔记为基础增加修改,直接上代码:
pom.xml Redis相关依赖:
4.0.0
com.vic
vic
0.1.0
1.7
org.springframework.boot
spring-boot-starter-parent
1.3.8.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis
mybatis-spring
1.2.2
org.mybatis
mybatis
3.2.8
mysql
mysql-connector-java
com.mchange
c3p0
0.9.2.1
org.springframework.boot
spring-boot-starter-redis
com.google.code.gson
gson
org.springframework.boot
spring-boot-maven-plugin
application.properties增加redis相关属性:
#datasource
spring.datasource.jdbcUrl=jdbc:mysql://115.28.92.178:3306/wms?useUnicode\=true&characterEncoding\=utf8;autoReconnect\=true;maxReconnects\=10;connectTimeout\=180000;socketTimeout\=180000
spring.datasource.user=root
spring.datasource.password=xx
spring.datasource.driverClass=com.mysql.jdbc.Driver
spring.datasource.maxActive=100
spring.datasource.initialPoolSize=5
spring.datasource.minPoolSize=5
spring.datasource.maxPoolSize=20
spring.datasource.maxStatements=100
spring.datasource.maxIdleTime=3600
spring.datasource.acquireIncrement=2
spring.datasource.acquireRetryAttempts=10
spring.datasource.acquireRetryDelay=600
spring.datasource.testConnectionOnCheckin=true
spring.datasource.idleConnectionTestPeriod=1200
spring.datasource.checkoutTimeout=100000
#redis
spring.redis.hostName=115.28.92.178
spring.redis.port=6379
spring.redis.password=xxx
spring.redis.pool.maxActive=8
spring.redis.pool.maxWait=-1
spring.redis.pool.maxIdle=8
spring.redis.pool.minIdle=0
spring.redis.timeout=0
com.vic.config包中新增RedisConfig.java:
/**
*
* @author vic
* @desc redis config bean
*
*/
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
private static Logger logger = Logger.getLogger(RedisConfig.class);
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisConnectionFactory getConnectionFactory(){
JedisConnectionFactory factory = new JedisConnectionFactory();
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
logger.info("JedisConnectionFactory bean init success.");
return factory;
}
@Bean
public RedisTemplate, ?> getRedisTemplate(){
RedisTemplate,?> template = new StringRedisTemplate(getConnectionFactory());
return template;
}
}
OK,此时Reddis已经集成完成,下面来对常用操作做一些封装测试:
新增IRedisService接口定义一些常用操作接口,以及添加实现类RedisServiceImpl,代码如下:
IRedisService.java
/**
*
* @author vic
* @desc redis service
*/
public interface IRedisService {
public boolean set(String key, String value);
public String get(String key);
public boolean expire(String key,long expire);
public boolean setList(String key ,List list);
public List getList(String key,Class clz);
public long lpush(String key,Object obj);
public long rpush(String key,Object obj);
public String lpop(String key);
}
RedisServiceImpl.java
/**
*
* @author vic
* @desc resdis service
*
*/
@Service
public class RedisServiceImpl implements IRedisService{
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean set(final String key, final String value) {
boolean result = redisTemplate.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer serializer = redisTemplate.getStringSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
return true;
}
});
return result;
}
public String get(final String key){
String result = redisTemplate.execute(new RedisCallback() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer serializer = redisTemplate.getStringSerializer();
byte[] value = connection.get(serializer.serialize(key));
return serializer.deserialize(value);
}
});
return result;
}
@Override
public boolean expire(final String key, long expire) {
return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
@Override
public boolean setList(String key, List list) {
String value = JSONUtil.toJson(list);
return set(key,value);
}
@Override
public List getList(String key,Class clz) {
String json = get(key);
if(json!=null){
List list = JSONUtil.toList(json, clz);
return list;
}
return null;
}
@Override
public long lpush(final String key, Object obj) {
final String value = JSONUtil.toJson(obj);
long result = redisTemplate.execute(new RedisCallback() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer serializer = redisTemplate.getStringSerializer();
long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
return count;
}
});
return result;
}
@Override
public long rpush(final String key, Object obj) {
final String value = JSONUtil.toJson(obj);
long result = redisTemplate.execute(new RedisCallback() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer serializer = redisTemplate.getStringSerializer();
long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
return count;
}
});
return result;
}
@Override
public String lpop(final String key) {
String result = redisTemplate.execute(new RedisCallback() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer serializer = redisTemplate.getStringSerializer();
byte[] res = connection.lPop(serializer.serialize(key));
return serializer.deserialize(res);
}
});
return result;
}
}
其中的JSONUtil类,可下载demo代码查看,其实就是一个JSON的工具类。
在ExampleController中添加测试方法:
@RestController
public class ExampleController {
@Autowired
private IUserService userService;
@Autowired
private IRedisService redisService;
@RequestMapping("/users")
public ResponseModal users(){
List users = userService.getAll();
ResponseModal modal = new ResponseModal(200,true,"",users);
return modal;
}
@RequestMapping("/redis/set")
public ResponseModal redisSet(@RequestParam("value")String value){
boolean isOk = redisService.set("name", value);
return new ResponseModal(isOk ? 200 : 500, isOk, isOk ? "success" : "error" , null);
}
@RequestMapping("/redis/get")
public ResponseModal redisGet(){
String name = redisService.get("name");
return new ResponseModal(200, true,"success",name);
}
}
运行Application的main函数
浏览器输入:http://localhost:8080/redis/set?value=vic 响应结果:
{"code":200,"success":true,"message":"success","response":null}
浏览器输入:http://localhost:8080/redis/get 响应结果:
{"code":200,"success":true,"message":"success","response":"vic"}
示例代码下载