本文介绍spring boot整合redis的一个简单的dome,可方便大家直接使用。文中包括redis五种类型的添加和查询功能,其余功能没能一一列出来查看请看文章末尾。
项目图片.pngredis的依赖包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
</dependencies>
二、application.yml配置文件(使用yml或者properties 都行)
spring:
# redis缓存
redis:
# Redis开关/默认关闭
enabled: true
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6380
password:
jedis:
pool:
# 连接池中的最小空闲连接
min-idle: 8
# 连接池中的最大空闲连接
max-idle: 500
# 连接池最大连接数(使用负值表示没有限制)
max-active: 2000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 10000
# 连接超时时间(毫秒)
timeout: 10000
三、存取乱码过滤
public class RedisCacheConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
ParserConfig.getGlobalInstance().addAccept("com.xiaolyuh.");
// 设置值(value)的序列化采用FastJsonRedisSerializer。
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
四、RedisUtils 类 (测试类使用)
public class RedisUtil {
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
// 如果使用RedisTemplate需要更改序列化方式
public void tt() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer );
redisTemplate.setValueSerializer(stringSerializer );
redisTemplate.setHashKeySerializer(stringSerializer );
redisTemplate.setHashValueSerializer(stringSerializer );
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* String类型 取
* 根据 key 获取对应的value 如果key不存在则返回null
*
* @param key 查询的key
* @return 查询结果
*/
public String get(final String key) {
Object result = null;
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
if (result == null) {
return null;
}
return result.toString();
}
/** String类型 存
*
*设置 key 的值为 value
*如果key不存在添加key 保存值为value
*如果key存在则对value进行覆盖
*
* @param key key值
* @param value 存入的value值
* @return 添加结果
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** map类型 存
* 为散列添加多个key-value键值对
* @param key key值
* @param value map值
* @return 添加结果
*/
public boolean hmset(String key, Map<String, String> value) {
boolean result = false;
try {
//putAll 添加多个key-value 添加一个使用put(H key, HK hashKey, HV value)
redisTemplate.opsForHash().putAll(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**map类型 取
* 获取散列的key-value键值对集合
* @param key key值
* @return 查询结果
*/
public Map<String, String> hmget(String key) {
Map<String, String> result = null;
try {
result = redisTemplate.opsForHash().entries(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** list 类型 存
* 插入数据到list
*
* @param key key值
* @param list value值
* @return 添加结果
*/
public boolean setList(String key , List<String> list) {
boolean result = false;
try {
ListOperations listOperations = redisTemplate.opsForList();
//从list头部插入value
listOperations.leftPush(key,list);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** list 类型 取
* 根据下标获取指定list数据
*
* @param key key值
* @param index 下标值
* @return 查询结果
*/
public String getList(final String key ,Long index) {
Object result = null;
redisTemplate.setValueSerializer(new StringRedisSerializer());
ListOperations listOperations = redisTemplate.opsForList();
//获取指定下标数据 使用range(0 -1)可以获取所有数据
result = listOperations.index(key ,index);
if (result == null) {
return null;
}
return result.toString();
}
/** set 类型 存
* 给集合key添加值,集合不存在创建后再添加
*
* @param key key值
* @param set value值
* @return 添加结果
*/
public boolean setSet(String key , Set<String> set) {
boolean result = false;
try {
SetOperations setOperations = redisTemplate.opsForSet();
//可添加多个
setOperations.add(key,set.toString());
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** set 类型 取
* 获取所有set值
*
* @param key key值
* @return 查询结果
*/
public String getSet(final String key) {
Object result = null;
redisTemplate.setValueSerializer(new StringRedisSerializer());
SetOperations listOperations = redisTemplate.opsForSet();
//查询所有
result = listOperations.members(key);
if (result == null) {
return null;
}
return result.toString();
}
/** ZSet 类型 存
* 给有序集合添加一个指定分数的成员 如果成员存在则覆盖
*
* @param key key值
* @param value value值
* @param score 分数
* @return 添加结果
*/
public boolean setZSet(String key , String value ,double score) {
boolean result = false;
try {
ZSetOperations setOperations = redisTemplate.opsForZSet();
setOperations.add(key,value,score);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** ZSet 类型 取
* 获取指定范围内数据
*
* @param key
* @param start
* @param end
* @return 查询数据
*/
public Set<String> getZSet(final String key ,long start ,long end) {
Object result = null;
redisTemplate.setValueSerializer(new StringRedisSerializer());
ZSetOperations listOperations = redisTemplate.opsForZSet();
// result = listOperations.rangeWithScores(key ,start ,end); //获取有序集合中指定分数范围内的成员集合 获取 value 分数
result = listOperations.reverseRange(key ,start ,end); //从有序集合中获取指定范围内从高到低的成员集合 获取 value
// result = listOperations.range(key ,start ,end); //指定范围内 (0 -1)返回所有。
if (result == null) {
return null;
}
// return result.toString();
Iterator iterator = ((Set) result).iterator();
Set<String> zSetValList = new HashSet<>();
while (iterator.hasNext()){
//使用rangeWithScores 方法获取的
// DefaultTypedTuple next = (DefaultTypedTuple)iterator.next();
// System.out.println();
// System.out.println(next.getScore());
// System.out.println(next.getValue());
//使用reverseRange 方法获取
String next = (String)iterator.next();
zSetValList.add(next);
}
return zSetValList;
}
}
五、测试demo
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisUtilTest {
@Autowired
private RedisUtil redisUtil;
@Test
public void testSet() {
// String
String value = "sdd";
redisUtil.set("String", value);
System.out.println(redisUtil.get("String"));
// map
Map<String ,String> map = new HashMap<>();
map.put("1","22");
map.put("11","22");
map.put("11","22");
map.put("666","6666");
redisUtil.hmset("map" ,map);
System.out.println(redisUtil.hmget("map"));
// list
List<String> list = new ArrayList<>();
list.add("11");
list.add("22");
list.add("666");
redisUtil.setList("list" ,list);
System.out.println(redisUtil.getList("list",0l));
// set
Set<String> set = new HashSet<>();
set.add("11");
set.add("22");
set.add("33");
redisUtil.setSet("set" ,set);
System.out.println(redisUtil.getSet("set"));
//zset
redisUtil.setZSet("zset","111",1d);
redisUtil.setZSet("zset","222",2d);
redisUtil.setZSet("zset","333",3d);
redisUtil.setZSet("zset","444",4d);
redisUtil.setZSet("zset","555",6d);
redisUtil.setZSet("zset","666",5d);
Set<String> zSetVal = redisUtil.getZSet("zset", 0, 5);
}
}
关于各类型的其他操作,可以根据redisUtils中的redisTemplate来调用 对应的类方法每个类型有一个对应的实体类
对应实体类方法作用链接地址:
String
https://blog.csdn.net/pengdandezhi/article/details/78902580
map
https://blog.csdn.net/pengdandezhi/article/details/78909869
list
https://blog.csdn.net/pengdandezhi/article/details/78903625
set
https://blog.csdn.net/pengdandezhi/article/details/78909041
zset
https://blog.csdn.net/pengdandezhi/article/details/78911049
网友评论