本篇基于Springboot2.0 + Redis实现数据缓存以及分库存储,首先我们要知道,Springboot整合Redis有两种方式,分别是Jedis和RedisTemplate,这两者有何区别?
Jedis是Redis官方推荐的面向Java的操作Redis的客户端,而RedisTemplate是SpringDataRedis中对JedisApi的高度封装。其实在Springboot的官网上我们也能看到,官方现在推荐的是SpringDataRedis形式,相对于Jedis来说可以方便地更换Redis的Java客户端,其比Jedis多了自动管理连接池的特性,方便与其他Spring框架进行搭配使用如:SpringCache。
首先我们看下整个项目的目录结构,共分为三部分,pom包在文末给出
#Matser的ip地址
redis.hostName=localhost
#端口号
redis.port=6379
#如果有密码
redis.password=123456
#客户端超时时间单位是毫秒 默认是2000
redis.timeout=10000
#最大空闲数
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
#redis.maxActive=600
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
redis.maxTotal=1000
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWaitMillis=1000
#连接的最小空闲时间 默认1800000毫秒(30分钟)
redis.minEvictableIdleTimeMillis=300000
#每次释放连接的最大数目,默认3
redis.numTestsPerEvictionRun=1024
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
redis.timeBetweenEvictionRunsMillis=30000
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true
#在空闲时检查有效性, 默认false
redis.testWhileIdle=true
这些配置并不一定都需要,按照情况添加,全都添加也无大碍,其中我们必须要指定Redis的地址,端口及密码
package com.springboot.demo.base.config;
import com.springboot.demo.base.utils.FastJson2JsonRedisSerializer;
import com.springboot.demo.base.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import com.springboot.demo.base.utils.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @ClassName: RedisConfig
* @Auther: zhangyingqi
* @Date: 2018/8/28 11:07
* @Description:
*/
@Configuration
@PropertySource("classpath:redis.properties")
@Slf4j
public class RedisConfig {
@Value("${redis.hostName}")
private String hostName;
@Value("${redis.password}")
private String password;
@Value("${redis.port}")
private Integer port;
@Value("${redis.maxIdle}")
private Integer maxIdle;
@Value("${redis.timeout}")
private Integer timeout;
@Value("${redis.maxTotal}")
private Integer maxTotal;
@Value("${redis.maxWaitMillis}")
private Integer maxWaitMillis;
@Value("${redis.minEvictableIdleTimeMillis}")
private Integer minEvictableIdleTimeMillis;
@Value("${redis.numTestsPerEvictionRun}")
private Integer numTestsPerEvictionRun;
@Value("${redis.timeBetweenEvictionRunsMillis}")
private long timeBetweenEvictionRunsMillis;
@Value("${redis.testOnBorrow}")
private boolean testOnBorrow;
@Value("${redis.testWhileIdle}")
private boolean testWhileIdle;
/**
* @auther: zhangyingqi
* @date: 17:52 2018/8/28
* @param: []
* @return: org.springframework.data.redis.connection.jedis.JedisConnectionFactory
* @Description: Jedis配置
*/
@Bean
public JedisConnectionFactory JedisConnectionFactory(){
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
redisStandaloneConfiguration.setHostName(hostName);
redisStandaloneConfiguration.setPort(port);
//由于我们使用了动态配置库,所以此处省略
//redisStandaloneConfiguration.setDatabase(database);
redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));
JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration,
jedisClientConfiguration.build());
return factory;
}
/**
* @auther: zhangyingqi
* @date: 17:52 2018/8/28
* @param: [redisConnectionFactory]
* @return: com.springboot.demo.base.utils.RedisTemplate
* @Description: 实例化 RedisTemplate 对象
*/
@Bean
public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
log.info("RedisTemplate实例化成功!");
RedisTemplate redisTemplate = new RedisTemplate();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* @auther: zhangyingqi
* @date: 17:52 2018/8/28
* @param: []
* @return: org.springframework.data.redis.serializer.RedisSerializer
* @Description: 引入自定义序列化
*/
@Bean
public RedisSerializer fastJson2JsonRedisSerializer() {
return new FastJson2JsonRedisSerializer
该类继承了springdataredis的RedisTemplate类,我们加入indexdb为Redis库的编号,重写了里面的RedisConnection方法,加入是否有库值传递进来的逻辑判断。
package com.springboot.demo.base.utils;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnection;
/**
* @ClassName: RedisTemplate
* @Auther: zhangyingqi
* @Date: 2018/8/28 16:15
* @Description: 重写RedisTemplate,加入选库
*/
public class RedisTemplate extends org.springframework.data.redis.core.RedisTemplate {
public static ThreadLocal indexdb = new ThreadLocal(){
@Override protected Integer initialValue() { return 0; }
};
@Override
protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
try {
Integer dbIndex = indexdb.get();
//如果设置了dbIndex
if (dbIndex != null) {
if (connection instanceof JedisConnection) {
if (((JedisConnection) connection).getNativeConnection().getDB().intValue() != dbIndex) {
connection.select(dbIndex);
}
} else {
connection.select(dbIndex);
}
} else {
connection.select(0);
}
} finally {
indexdb.remove();
}
return super.preProcessConnection(connection, existingConnection);
}
}
添加FastJson2JsonRedisSerializer.java,实现RedisSerializer接口,实现其中的序列化和反序列化方法。
package com.springboot.demo.base.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
* @ClassName: FastJson2JsonRedisSerializer
* @Auther: zhangyingqi
* @Date: 2018/8/28 16:11
* @Description: 自定义序列化
*/
public class FastJson2JsonRedisSerializer implements RedisSerializer {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class clazz;
public FastJson2JsonRedisSerializer(Class clazz) {
super(); this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
}
}
其中内容不具备分库操作的,所以我对其进行了改造,使得最终我们可以根据需要向不同的库中存储数据。
package com.springboot.demo.base.utils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import com.springboot.demo.base.utils.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@Lazy
@Component
public class RedisUtil{
@Autowired
private RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
//=============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key, int indexdb){
redisTemplate.indexdb.set(indexdb);
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,Object value,int indexdb) {
try {
redisTemplate.indexdb.set(indexdb);
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
redisTemplate.opsForValue().set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param by 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param by 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map
具体的改造过程示例:
public boolean set(String key,Object value,int indexdb) {
try {
redisTemplate.indexdb.set(indexdb);
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
这是一个最基本的set方法,加入int型的indexdb参数,用来接收库编号,通过redisTemplate.indexdb.set(indexdb);完成选库操作,由于我们在内部使用finally清除了选库,所以不必担心下次操作库的缓存问题。
依次在你需要改造的地方做对应的修改即可。
我这里直接拿现成的controller做演示,不再独立编写测试类
新建RedisTestController.java
package com.springboot.demo.controller;
import com.springboot.demo.base.controller.BaseController;
import com.springboot.demo.base.utils.RedisConstants;
import com.springboot.demo.base.utils.RedisUtil;
import com.springboot.demo.base.utils.StateParameter;
import com.springboot.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @ClassName: RedisTestController
* @Auther: zhangyingqi
* @Date: 2018/8/28 17:24
* @Description:
*/
@Controller
@RequestMapping("/redis")
public class RedisTestController extends BaseController{
@Autowired
RedisUtil redisUtil;
/**
* @auther: zhangyingqi
* @date: 17:26 2018/8/28
* @param: []
* @return: org.springframework.ui.ModelMap
* @Description: 测试redis存储&读取
*/
@RequestMapping(value="/test")
@ResponseBody
public ModelMap test(){
try {
redisUtil.set("redisTemplate","这是一条测试数据", RedisConstants.datebase2);
String value = redisUtil.get("redisTemplate",RedisConstants.datebase2).toString();
logger.info("redisValue="+value);
logger.info("读取redis成功");
return getModelMap(StateParameter.SUCCESS, value, "操作成功");
} catch (Exception e) {
e.printStackTrace();
return getModelMap(StateParameter.FAULT, null, "操作失败");
}
}
@RequestMapping(value="/setUser")
@ResponseBody
public ModelMap setUser(){
try {
User user = new User();
user.setName("隔壁老王");
user.setAge(28);
user.setId(getUuid());
redisUtil.set("user",user, RedisConstants.datebase1);
User res = (User)redisUtil.get("user",RedisConstants.datebase1);
logger.info("res="+res.toString());
logger.info("读取redis成功");
return getModelMap(StateParameter.SUCCESS, res, "操作成功");
} catch (Exception e) {
e.printStackTrace();
return getModelMap(StateParameter.FAULT, null, "操作失败");
}
}
}
这里使用@Autowired注入RedisUtil
@Autowired
RedisUtil redisUtil;
使用以下语句将字符串存入redis的库2中
redisUtil.set("redisTemplate","这是一条测试数据", RedisConstants.datebase2);
启动项目执行操作,后台可以看到实例化成功
输入测试地址:http://localhost:8080/redis/test,返回成功,打开redis客户端工具,可以看到在db2中存入了该数据
最后给出pom包
4.0.0
com.springboot
springbootRedis
0.0.1-SNAPSHOT
war
springbootRedis
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.4.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-tomcat
org.springframework.boot
spring-boot-starter-data-jpa
org.hibernate
hibernate-entitymanager
org.hibernate
hibernate-core
org.hibernate
hibernate-core
5.2.10.Final
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
redis.clients
jedis
2.9.0
commons-io
commons-io
2.6
com.alibaba
fastjson
1.2.38
org.springframework.boot
spring-boot-maven-plugin
原文:https://blog.csdn.net/zhulier1124/article/details/82154937
GitHub地址:https://github.com/jwwam/springbootRedis.git