概述
SpringBoot2.0整合redis
springboot的自动化配置。
首先,如果你采用maven来构建项目,那么在pom文件中添加如下依赖:
这里要注意版本问题,下面两个版本测试没有问题
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
配置application.properties文件
这里我们实现三个redis配置
# REDIS
spring.redis.mooc.host=ip
spring.redis.icve.host=ip
spring.redis.zjy.host=ip
spring.redis.mooc.port=6379
spring.redis.icve.port=6379
spring.redis.zjy.port=6379
spring.redis.mooc.password=password
spring.redis.icve.password=password
spring.redis.zjy.password=password
RedisTemplateConfig代码如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisTemplateConfig {
//mooc
@Value("${spring.redis.mooc.host}")
private String moocHost;
@Value("${spring.redis.mooc.port}")
private String moocPort;
@Value("${spring.redis.mooc.password}")
private String moocPassword;
//icve
@Value("${spring.redis.icve.host}")
private String icveHost;
@Value("${spring.redis.icve.port}")
private String icvePort;
@Value("${spring.redis.icve.password}")
private String icvePassword;
//zjy
@Value("${spring.redis.zjy.host}")
private String zjyHost;
@Value("${spring.redis.zjy.port}")
private String zjyPort;
@Value("${spring.redis.zjy.password}")
private String zjyPassword;
//下面参数也可以配置在application.properties文件中
private static final int MAX_IDLE = 1000; //最大空闲连接数
private static final int MAX_TOTAL = 1024; //最大连接数
private static final long MAX_WAIT_MILLIS = 100000; //建立连接最长等待时间
//连接池配置
@Bean
public JedisPoolConfig jedisPoolConfig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxWaitMillis(maxWaitMillis);
poolConfig.setTestOnBorrow(testOnBorrow);
return poolConfig;
}
@Bean
public RedisConnectionFactory redisConnectionFactory(String host, int port, String password, int maxIdle,
int maxTotal, long maxWaitMillis, int index) {
RedisStandaloneConfiguration redisStandaloneConfiguration =
new RedisStandaloneConfiguration();
//设置redis服务器的host或者ip地址
redisStandaloneConfiguration.setHostName(host);
//设置默认使用的数据库
redisStandaloneConfiguration.setDatabase(index);
//设置密码
redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
//设置redis的服务的端口号
redisStandaloneConfiguration.setPort(port);
//获得默认的连接池构造器(怎么设计的,为什么不抽象出单独类,供用户使用呢)
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb =
(JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();
//指定jedisPoolConifig来修改默认的连接池构造器(真麻烦,滥用设计模式!)
jpcb.poolConfig(jedisPoolConfig(maxIdle, maxTotal, maxWaitMillis, false));
//通过构造器来构造jedis客户端配置
JedisClientConfiguration jedisClientConfiguration = jpcb.build();
//单机配置 + 客户端配置 = jedis连接工厂
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}
//------------------------------------
@Bean(name = "redisMoocTemplate")
public StringRedisTemplate redisMoocTemplate() {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(
redisConnectionFactory(moocHost, Integer.parseInt(moocPort), moocPassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, 0));
return template;
}
//------------------------------------
@Bean(name = "redisIcveTemplate")
public StringRedisTemplate redisIcveTemplate() {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(
redisConnectionFactory(icveHost, Integer.parseInt(icvePort), icvePassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, 0));
return template;
}
//------------------------------------
@Bean(name = "redisZjyTemplate")
public StringRedisTemplate redisZjyTemplate() {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(
redisConnectionFactory(zjyHost, Integer.parseInt(zjyPort), zjyPassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, 0));
return template;
}
}
调用方法如下:
//在类中进行引用
@Resource(name = "redisMoocTemplate")
StringRedisTemplate redisMoocTemplate;
@Resource(name = "redisIcveTemplate")
StringRedisTemplate redisIcveTemplate;
@Resource(name = "redisZjyTemplate")
StringRedisTemplate redisZjyTemplate;
//在方法中直接调用函数即可
//判断key是否存在
redisMoocTemplate.hasKey("keyyesy");
调试报错解决
1.spring-data-redis 与 jedis 版本匹配问题 spring-data-redis2.0.4搭配jedis 3.0.1会报错,替换一个较低版本的jedis 2.9.0
具体报错
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in file [D:developspringfirsttargetclassesspringapplicationContext-redis.xml]: Cannot resolve reference to bean 'jedisConnectionFactory' while setting bean property 'connectionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisConnectionFactory': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.data.redis.connection.jedis.JedisConnectionFactory] from ClassLoader [WebappClassLoader
2.获取redis连接超时
redis-错误:redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out
问题:redis是基于内存的,所以一般来说反应速度是毫秒级的,但是在本机开发测试的时候遇到大的数量及访问或者是高频的访问会造成socket的延时增加到秒级,由我们知道默认的超时时间是2秒,所以有可能会造成如上错误
解决:在创建JedisPool时,在JedisPool构造方法中的最后一个参数传入socket的超时时间,将超时时间设置的稍微长一些
StringRedisTemplate常用操作
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间
stringRedisTemplate.boundValueOps("test").increment(-1);//val做-1操作
stringRedisTemplate.opsForValue().get("test")//根据key获取缓存中的val
stringRedisTemplate.boundValueOps("test").increment(1);//val +1
stringRedisTemplate.getExpire("test")//根据key获取过期时间
stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根据key获取过期时间并换算成指定单位
stringRedisTemplate.delete("test");//根据key删除缓存
stringRedisTemplate.hasKey("546545");//检查key是否存在,返回boolean值
stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//向指定key中存放set集合
stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//设置过期时间
stringRedisTemplate.opsForSet().isMember("red_123", "1")//根据key查看集合中是否存在指定数据
stringRedisTemplate.opsForSet().members("red_123");//根据key获取set集合
RedisTemplate Api总结
一、 通用操作工具
1、常用的分布式锁加强版
/**
* 最终加强分布式锁
* @param key key值
* @return 是否获取到
*/
public boolean lock(String key) {
String lock = LOCK_PREFIX + key;
// 利用lambda表达式
return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
Boolean acquire = redisConnection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
if (acquire) {
return true;
} else {
byte[] value = redisConnection.get(lock.getBytes());
if (Objects.nonNull(value) && value.length > 0) {
long expireTime = Long.parseLong(new String(value));
if (expireTime < System.currentTimeMillis()) {
// 如果锁已经过期
byte[] oldValue = redisConnection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
// 防止死锁
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
}
});
}
2、 删除锁
/**
* 删除锁
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
3、指定缓存失效时间
/**
* 指定缓存失效时间
* @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;
}
}
4、根据key 获取过期时间
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
5、判断key是否存在
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
6、删除缓存
/**
* 删除缓存
* @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类型相关操作
1、获取缓存
/**
* 获取缓存
* @param key 键
* @return 值
*/
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
2、添加缓存
/**
* 添加缓存
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
3、添加缓存并设置过期时间
/**
* 添加缓存并设置过期时间
* @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{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
4、递增操作
/**
* 递增
* @param key 键
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
5、递减操作
/**
* 递减
* @param key 键
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
三、 哈希类型相关操作
1、设置一组Map的键值对
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
2、获取指定Map的所有键值对
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
3、添加一个Map类型值
/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
4、添加一个Map类型值并设置过期时间
/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
5、 向一张hash表中放入数据,如果不存在将创建
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
6、向一张hash表中放入数据,如果不存在将创建并设置过期时间
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒)
注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
7、删除hash表中的值
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item){
redisTemplate.opsForHash().delete(key,item);
}
8、判断hash表中是否有该项的值
/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}
9、递增,如果不存在,就会创建一个 并把新增后的值返回
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}
10、递减
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}
四、 SET类型相关操作
1、根据key获取Set中的所有值
/**
* 根据key获取Set中的所有值
* @param key 键
* @return
*/
public Set<Object> sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
2、根据value从一个set中查询,是否存在
/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
3、添加一个SET缓存
/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object...values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
4、添加一个SET缓存并设置过期时间
/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key,long time,Object...values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0) expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
5、获取SET缓存的长度
/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
6、移除指定key的缓存
/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
五、 LIST类型相关操作
1、获取list缓存的内容
/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束
0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key,long start, long end){
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
2、 获取list缓存的长度
/**
* 获取list缓存的长度
* @param key 键
* @return
*/
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
3、通过索引 获取list中的值
/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引
index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
4、 将list放入缓存
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
5、将list放入缓存并设置过期时间
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
6、将list放入缓存
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
7、将list放入缓存并设置过期时间
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
8、根据索引修改list中的某条数据
/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
9、移除N个值为value
/**
* 移除N个值为value
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
参考连接:
https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/connection/jedis/JedisConnectionFactory.html
https://www.cnblogs.com/muxi0407/p/11845016.html
最后
以上就是自信路灯为你收集整理的SpringBoot2.0实现多个Redis配置的RedisTemplate使用实例全解SpringBoot2.0整合redisRedisTemplate Api总结的全部内容,希望文章能够帮你解决SpringBoot2.0实现多个Redis配置的RedisTemplate使用实例全解SpringBoot2.0整合redisRedisTemplate Api总结所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复