SpringBoot整合Redis
-
SpringBoot整合Redis
- 1. 说明
-
2. 整合测试
-
3. 自定义RedisTemplate
- 1. 关于序列化
- 2. 自定义RedisTemplate
-
4. 编写Redis工具类
1. 说明
package org.springframework.boot.autoconfigure.data.redis;
import java.net.UnknownHostException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class,JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
//如果redisTemplate存在,则默认的模板不生效 ==> 我们可以自己定义一个 来替换这个默认的
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
//默认的 RedisTemplate 没有过多的设置,redis 对象都是需要序列化
//两个泛型都是 Object,Object 的类型,我们使用都需要强制转换!
RedisTemplate<Object,Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
//由于String是Redis中最常用的,所以单独提出来了一个Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
2. 整合测试
1. 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
如果要使用连接池,要导入如下依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2. 配置连接
# 配置Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
# SpringBoot 2.X 版本使用Lettuce,因此不要配置Jedis!
spring.redis.lettuce.pool.max-active=8
3. 测试
package com.wang.redis02srpingboot;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SrpingbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
//操作不同的数据类型
//opsForValue 操作字符串 类似 String,其中Bitmap也在这个方法下面,可以.setBit()方法
//opsForList list
//opsForSet set
//opsForHash hashmap
//opsForZset Zset
//opsForGeo geo
//opsForHyperLogLog hyperloglog
/*
redisTemplate.opsForValue().setBit("sign",true);
*/
//除了基本的操作,我们常用的方法都可以直接通过RedisTemplate来操作,比如事务和基本的CRUD
//获取Redis的连接对象
/*
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushAll();
*/
redisTemplate.opsForValue().set("myKey","我的RedisValue");
System.out.println(redisTemplate.opsForValue().get("myKey"));
}
}
这里有几点需要注意
-
String在opsForValue()下,同时,BitMap也被放在了这个方法下面!
-
用getConnectionFactory().getConnection()获得连接对象,可以对数据库进行清理或者关闭
-
要使用连接池,除了SpringBoot导入的几个依赖,我们还要导入 commons-pool2 这个依赖,因为Lettuce和Jedis都使用了这个技术进行连接池的实现!
-
默认的序列化方式是利用JDK进行序列化,会导致中文显示的问题,因此我们有必要自定义RedisTemplate
3. 自定义RedisTemplate
1. 关于序列化

可以看出,没有序列化直接传递对象会报错
@Test
void test() throws JsonProcessingException {
//真实的开发一般使用JSON传递对象,这里用SpringBoot自带的Jackson
User user = new User("测试用户",3);
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",jsonUser);
System.out.println(redisTemplate.opsForValue().get("user"));
}
输出了JSON字符串

package com.wang.redis02srpingboot.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
//在企业中,我们所有哦的pojo都会序列化
public class User implements Serializable {
private String name;
private int age;
}

2. 自定义RedisTemplate
由于SpringBoot默认实现的RedisTemplate使用的是JDK的序列化,我们想用自己的序列化方法就要自定义自己的RedisTemplate
package com.wang.redis02srpingboot.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
//固定的模板
@Configuration
public class RedisConfig {
//编写我们自己的RedisTemplate
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory) throws UnknownHostException {
// 为了我们自己开发方便,一般直接使用 <String,Object>
RedisTemplate<String,Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 序列化配置
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
//配置所有的成员变量无需注解就可以完成序列化,这里的 PropertyAccessor 和 Visibility 都是枚举类型
objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
//指定序列化的类型,原来的enableDefaultTyping方法过期了,这里主要指定第二个参数
//NON_FINAL ==> 整个类,除final外的的属性信息都需要被序列化和反序列化
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL,JsonTypeInfo.As.WRAPPER_ARRAY);
//使配置的ObjectMapper生效
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//配置具体的序列化方式
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
//hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
//使设置的template生效
template.afterPropertiesSet();
return template;
}
}
4. 编写Redis工具类
1. 工具类
为了简化操作,我们封装工具类
注意,要把这个类托管到SpringBoot中!
package com.wang.redis02srpingboot.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate<String,Object> redisTemplate;
// ===================== common =====================
/**
* 指定缓存失效的时间
* @param key 键
* @param time 时间(秒)
*/
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 可以传一个或者多个值
*/
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));
}
}
}
/**
* 清除当前数据库的缓存
*/
public void flushdb() {
redisTemplate.getConnectionFactory()
.getConnection()
.flushDb();
}
/**
* 清空全部数据库
*/
public void flushall() {
redisTemplate.getConnectionFactory()
.getConnection()
.flushAll();
}
/**
* 切换数据库
* @param dbindex 数据库的编号
*/
public void select(int dbindex) {
redisTemplate.getConnectionFactory()
.getConnection()
.select(dbindex);
}
// ===================== String =====================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @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;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒),time要大于0,如果time小于等于0,将设置无限期
* @return true成功,Object value,long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key,value,TimeUnit.SECONDS);
} else {
set(key,value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
*/
public long incr(String key,long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key,delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
*/
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<Object,Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet 设置一个或者多个map
* @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;
}
}
/**
* HashSet 设置一个或者多个map并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key,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;
}
}
/**
* 向一张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;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建,并设置时间
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key,long time) {
try {
redisTemplate.opsForHash().put(key,value);
if (time > 0) {
expire(key,time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key,Object... item) {
redisTemplate.opsForHash().delete(key,item);
}
/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hexists(String key,String item) {
return redisTemplate.opsForHash().hasKey(key,item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return 274
*/
public double hincr(String key,double by) {
return redisTemplate.opsForHash().increment(key,by);
}
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
*/
public double hdecr(String key,-by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
* @param key 键
*/
public Set<Object> sget(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sexists(String key,Object value) {
try {
return redisTemplate.opsForSet().isMember(key,value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sadd(String key,Object... values) {
try {
return redisTemplate.opsForSet().add(key,values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存,并设置时间
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sadd(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;
}
}
/**
* 获取set缓存的长度
* @param key 键
*/
public long scard(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的元素
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long srem(String key,Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key,values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
*/
public List<Object> lrange(String key,long start,long end) {
try {
return redisTemplate.opsForList().range(key,start,end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key 键
*/
public long llen(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
*/
public Object lindex(String key,long index) {
try {
return redisTemplate.opsForList().index(key,index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* rpush 将元素插入队尾
* @param key 键
* @param value 值
*/
public boolean rpush(String key,Object value) {
try {
redisTemplate.opsForList().rightPush(key,value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将元素插入队尾,并设定时间
* @param key 键
* @param value 值
* @param time 时间(秒)
*/
public boolean rpush(String key,long time) {
try {
redisTemplate.opsForList().rightPush(key,value);
if (time > 0)
expire(key,time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将元素插入队尾
* @param key 键
* @param value 值,list类型
*/
public boolean rpush(String key,List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key,List<Object> value,long time) {
try {
redisTemplate.opsForList().rightPushAll(key,time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* lpush 将元素插入队头
* @param key 键
* @param value 值
*/
public boolean lpush(String key,Object value) {
try {
redisTemplate.opsForList().leftPush(key,value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将元素插入队头,并设定时
* @param key 键
* @param value 值
* @param time 时间(秒)
*/
public boolean lpush(String key,long time) {
try {
redisTemplate.opsForList().leftPush(key,time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将元素插入队头
* @param key 键
* @param value 值,list类型
*/
public boolean lpush(String key,List<Object> value) {
try {
redisTemplate.opsForList().leftPushAll(key,并设定时间
* @param key 键
* @param value 值
* @param time 时间(秒)
*/
public boolean lpush(String key,long time) {
try {
redisTemplate.opsForList().leftPushAll(key,time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
*/
public boolean lset(String key,long index,Object value) {
try {
redisTemplate.opsForList().set(key,index,value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value的元素
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lrem(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key,count,value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ============================Zset=============================
/**
* 添加一个Zset
* @param key 键
* @param value 值
* @param score 编号
* @return 成功 true,失败false
*/
public boolean zadd (String key,Double score) {
try {
redisTemplate.opsForZSet().add(key,score);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 批量添加Zset
* @param key 键
* @param map value-score键值对
* @return 添加的个数
*/
public long zadd (String key,Map<Object,Double> map) {
try {
Set<ZSetOperations.TypedTuple<Object>> set = new HashSet<>();
for (Map.Entry<Object,Double> entry : map.entrySet()) {
DefaultTypedTuple defaultTypedTuple = new DefaultTypedTuple(entry.getKey(),entry.getValue());
set.add(defaultTypedTuple);
}
Long count = redisTemplate.opsForZSet().add(key,set);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
2. 测试
package com.wang.redis02srpingboot;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.redis02srpingboot.Utils.RedisUtil;
import com.wang.redis02srpingboot.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SrpingbootApplicationTests {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
@Autowired
private RedisUtil redisUtil;
@Test
void contextLoads() {
//操作不同的数据类型
//opsForValue 操作字符串 类似 String,"我的RedisValue");
System.out.println(redisTemplate.opsForValue().get("myKey"));
}
@Test
void test() throws JsonProcessingException {
//真实的开发一般使用JSON传递对象,这里用SpringBoot自带的Jackson
User user = new User("测试用户",3);
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",jsonUser);
System.out.println(redisTemplate.opsForValue().get("user"));
}
//利用我们自己封装的工具类测试
@Test
void test1() {
redisUtil.set("name","测试用户2");
System.out.println(redisUtil.get("name"));
}
}
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|