Spring-Boot 使用 Jedis 操作 Redis
背景:
1.Redis 之前学了个皮毛 还忘的差不多了,感觉公司项目中的Redis用的真的牛逼,so 需要深造。
2.有个同事在搞Jedis,勾起了我对知识的向往,不会用,但是很渴望。
过程:
1.改造原有项目集成Jedis,引入jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>
2.yml中配置Redis 大部分使用的是默认配置
redis:
database: 0
host: localhost
port: 6379
password:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 0
session:
store-type: none
3.编写Jedis配置类 JedisConfig
package com.zyt.creenshot.configs; import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* @ClassName JedisConfig
* @Description Jedis配置工具类 梦想家
* @Author Zhai XiaoTao https://www.cnblogs.com/zhaiyt
* @Date 2019/1/14 14:45
* @Version 1.0
*/
@Configuration
@Slf4j
@Data
public class JedisConfig extends CachingConfigurerSupport { @Value("${spring.redis.host}")
private String host; @Value("${spring.redis.port}")
private int port; @Value("${spring.redis.timeout}")
private int timeout; @Value("${spring.redis.pool.max-active}")
private int maxActive; @Value("${spring.redis.pool.max-idle}")
private int maxIdle; @Value("${spring.redis.pool.min-idle}")
private int minIdle; @Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis; @Bean
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setMaxTotal(maxActive);
jedisPoolConfig.setMinIdle(minIdle);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, null);
log.info("JedisPool注入成功!");
log.info("redis地址:" + host + ":" + port);
return jedisPool;
}
}
4.编写JedisUtil工具类 就前面几个有点用,后面的暂时还没找到用的地方
package com.zyt.creenshot.util; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import sun.plugin2.message.Serializer; import java.util.List;
import java.util.Map;
import java.util.Set; /**
* @ClassName JedisUtil
* @Description screenShot 梦想家
* @Author Zhai XiaoTao https://www.cnblogs.com/zhaiyt
* @Date 2019/1/14 15:04
* @Version 1.0
*/
@Component
public class JedisUtil { @Autowired
private JedisPool jedisPool; @Autowired(required = false)
private Serializer serializer; /**
* string类型
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
String back = jedis.set(key, value);
jedis.close();
return back;
} /**
* @return java.util.Set<java.lang.String>
* @Description <模糊获取key>
* @Author Zhaiyt
* @Date 20:02 2019/1/14
* @Param
**/
public Set<String> keys(String pattern) {
Jedis jedis = jedisPool.getResource();
Set<String> keys = jedis.keys(pattern);
jedis.close();
return keys;
} /**
* 删除key对应的value
*
* @param key
* @return
*/
public Long del(String key) {
Jedis jedis = jedisPool.getResource();
Long back = jedis.del(key);
jedis.close();
return back;
} /**
* 获取string类型
*
* @param key
* @return
*/
public String get(String key) {
Jedis jedis = jedisPool.getResource();
String back = jedis.get(key);
jedis.close();
return back;
} /**
* 将值 value 关联到 key ,并将 key 的生存时间设为 seconds (以秒为单位)。
*
* @param key
* @param seconds
* @param value
* @return
*/
public String setex(String key, int seconds, String value) {
Jedis jedis = jedisPool.getResource();
String back = jedis.setex(key, seconds, value);
jedis.close();
return back;
} /**
* 返回哈希表 key 中,所有的域和值。
* 在返回值里,紧跟每个域名(field name)之后是域的值(value),所以返回值的长度是哈希表大小的两倍。
*
* @param key
* @return
*/
public Map hgetAll(String key) {
Jedis jedis = jedisPool.getResource();
Map back = jedis.hgetAll(key);
jedis.close();
return back;
} /**
* 将哈希表 key 中的域 field 的值设为 value 。
* 如果 key 不存在,一个新的哈希表被创建并进行 HSET 操作。
* 如果域 field 已经存在于哈希表中,旧值将被覆盖。
*
* @param key
* @param field
* @param value
* @return
*/
public Long hset(String key, String field, String value) {
Jedis jedis = jedisPool.getResource();
Long back = jedis.hset(key, field, value);
jedis.close();
return back;
} /**
* 返回哈希表 key 中给定域 field 的值。
*
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
Jedis jedis = jedisPool.getResource();
String back = jedis.hget(key, field);
jedis.close();
return back;
} /**
* 删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param field
* @return
*/
public long hdel(String key, String field) {
Jedis jedis = jedisPool.getResource();
long back = jedis.hdel(key, field);
jedis.close();
return back;
} /**
* 将一个或多个值 value 插入到列表 key 的表头
*
* @param key
* @param value
* @return
*/
public Long lpush(String key, String... value) {
Jedis jedis = jedisPool.getResource();
Long back = jedis.lpush(key, value);
jedis.close();
return back;
} /**
* 将一个或多个值 value 插入到列表 key 的表尾
*
* @param key
* @param value
* @return
*/
public long rpush(String key, String... value) {
Jedis jedis = jedisPool.getResource();
long back = jedis.rpush(key, value);
jedis.close();
return back;
} /**
* 通过下标替换元素的内容
*
* @param key
* @param index
* @param value
* @return
*/
public String lset(String key, long index, String value) {
Jedis jedis = jedisPool.getResource();
String back = jedis.lset(key, index, value);
jedis.close();
return back;
} /**
* 移除有序集合lsit中的参数
* 0所有
*
* @param key
* @param count
* @param value
* @return
*/
public long lrem(String key, long count, String value) {
Jedis jedis = jedisPool.getResource();
long back = jedis.lrem(key, count, value);
jedis.close();
return back;
} /**
* 返回列表 key 的长度。
* 如果 key 不存在,则 key 被解释为一个空列表,返回 0 .
* 如果 key 不是列表类型,返回一个错误。
*
* @param key
* @return
*/
public Long llen(String key) {
Jedis jedis = jedisPool.getResource();
Long back = jedis.llen(key);
jedis.close();
return back;
} /**
* 返回列表 key 中指定区间内的元素
* -1 表示列表的最后一个元素
*
* @param key
* @param start
* @param end
* @return
*/
public List lrange(String key, int start, int end) {
Jedis jedis = jedisPool.getResource();
List back = jedis.lrange(key, start, end);
jedis.close();
return back;
} /**
* 将 key 中储存的数字值增一
*
* @param key
* @return
*/
public long incr(String key) {
Jedis jedis = jedisPool.getResource();
long back = jedis.incr(key);
jedis.close();
return back;
} /**
* 将 key 中储存的数字值减一。
*
* @param key
* @return
*/
public long decr(String key) {
Jedis jedis = jedisPool.getResource();
long back = jedis.decr(key);
jedis.close();
return back;
} /**
* 为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除。
*
* @param key
* @param seconds
* @return
*/
public long expire(String key, int seconds) {
Jedis jedis = jedisPool.getResource();
long back = jedis.expire(key, seconds);
jedis.close();
return back;
} /**
* 将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略。
*
* @param key
* @param value
* @return
*/
public long sadd(String key, String value) {
Jedis jedis = jedisPool.getResource();
long back = jedis.sadd(key, value);
jedis.close();
return back;
} /**
* 检查给定 key 是否存在。
*
* @param key
* @return
*/
public boolean exists(String key) {
Jedis jedis = jedisPool.getResource();
boolean back = jedis.exists(key);
jedis.close();
return back;
} /**
* 将一个或多个 member 元素及其 score 值加入到有序集 key 当中。
*
* @param key
* @param score
* @param member
* @return
*/
public double zadd(String key, double score, String member) {
Jedis jedis = jedisPool.getResource();
double back = jedis.zadd(key, score, member);
jedis.close();
return back;
} /**
* 返回有序集 key 中,所有 score 值介于 min 和 max 之间(包括等于 min 或 max )的成员。有序集成员按 score 值递增(从小到大)次序排列。
*
* @param key
* @param min
* @param max
* @return
*/
public Set getZrangeByScore(String key, String min, String max) {
Jedis jedis = jedisPool.getResource();
Set back = jedis.zrangeByScore(key, min, max);
jedis.close();
return back;
} /**
* 移除有序系列中的指定范围
*
* @param key
* @param start
* @param end
* @return
*/
public long delZremrangeByScore(String key, String start, String end) {
Jedis jedis = jedisPool.getResource();
long back = jedis.zremrangeByScore(key, start, end);
jedis.close();
return back;
} /**
* 有序集合
* 根据分数降序排列
*
* @param key
* @param max
* @param min
* @return
*/
public Set getZrevrangeByScore(String key, String max, String min) {
Jedis jedis = jedisPool.getResource();
Set back = jedis.zrevrangeByScore(key, max, min);
jedis.close();
return back;
} /**
* 有序集合
* score增加或减少值
*
* @param key
* @param score
* @param member
* @return
*/
public Double setZincrby(String key, double score, String member) {
Jedis jedis = jedisPool.getResource();
double back = jedis.zincrby(key, score, member);
jedis.close();
return back;
} /**
* 有序集合
* 降序排列
*
* @param key
* @param start
* @param end
* @return
*/
public Set getZrevrange(String key, long start, long end) {
Jedis jedis = jedisPool.getResource();
Set back = jedis.zrevrange(key, start, end);
jedis.close();
return back;
}
}
5.编写对象转字符串 和 字符串转对象公共方法
/**
* @Description <对象转string>
* @Author Zhaiyt
* @Date 19:34 2019/1/14
* @Param
* @return java.lang.String
**/
public static String objectToString(Object obj){
ObjectMapper objectMapper = new ObjectMapper();
String resultStr = null;
try {
resultStr = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("向Redis中写入数据时失败");
}
return resultStr;
} /**
* @Description <对象转string>
* @Author Zhaiyt
* @Date 19:34 2019/1/14
* @Param
* @return java.lang.String
**/
public static Object stringToObj(Class typeClass,Class clazz,String data){
ObjectMapper objectMapper = new ObjectMapper();
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(typeClass, clazz);
Object obj = null;
try {
obj = objectMapper.readValue(data, javaType);
} catch (IOException e) {
log.error("redis中读取数据失败");
}
return obj;
}
6.编写测试方法
/**
* @Description <Redis test method>
* @Author Zhaiyt
* @Date 20:57 2019/1/14
* @Param
* @return java.util.List<com.zyt.creenshot.entity.Record>
**/
@RequestMapping(value = "/findAll")
public List<Record> findAll() {
List<Record> allRecord = null;
if (jedisUtil.exists("findAll")) {
return (List<Record>) CommonUtils.stringToObj(List.class, Record.class, jedisUtil.get("findAll"));
} else {
allRecord = recordServiceImpl.findAllRecord();
String str = CommonUtils.objectToString(allRecord);
jedisUtil.set("findAll", str);
}
return allRecord;
}
7.编写清除缓存操作接口类
package com.zyt.creenshot.controller; import com.zyt.creenshot.util.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Set; /**
* @ClassName RedisController
* @Description Redis缓存操作接口 梦想家
* @Author Zhai XiaoTao https://www.cnblogs.com/zhaiyt
* @Date 2019/1/14 16:07
* @Version 1.0
*/
@RestController
@Slf4j
public class RedisController { @Autowired
private JedisUtil jedisUtil; /**
* @return void
* @Description <清空所有缓存>
* @Author Zhaiyt
* @Date 20:19 2019/1/14
* @Param
**/
@RequestMapping(value = "/refrashAllCache")
public void refrashAllCache() {
log.info("清空Redis缓存 ... start ... ");
Set<String> keys = jedisUtil.keys("*");
for (String key : keys) {
jedisUtil.del(key);
}
log.info("清空Redis缓存 ... end ... ");
} /**
* @return void
* @Description <清空制定key缓存>
* @Author Zhaiyt
* @Date 20:19 2019/1/14
* @Param
**/
@RequestMapping(value = "/refrashCacheByKey")
public void refrashCacheByKey(String key) {
log.info("删除 key 值为" + key + "的缓存 ... start ...");
Set<String> keys = jedisUtil.keys(key);
jedisUtil.del(key);
log.info("删除 key 值为" + key + "的缓存 ... end ...");
} /**
* @return void
* @Description <移除指定类型缓存>
* @Author Zhaiyt
* @Date 20:19 2019/1/14
* @Param
**/
@RequestMapping(value = "/refrashCacheByKeyType")
public void refrashCacheByKeyType(String keyType) {
log.info("删除类型为" + keyType + "的缓存 ... start ...");
Set<String> keys = jedisUtil.keys(keyType);
for (String key : keys) {
jedisUtil.del(key);
}
log.info("删除类型为" + keyType + "的缓存 ... end ...");
}
}
8.启动Redis忘记了... Redis 安装参照另一篇文章或参照 菜鸟网络的进行安装启动,测试 over
Spring-Boot 使用 Jedis 操作 Redis的更多相关文章
- Spring boot配置多个Redis数据源操作实例
原文:https://www.jianshu.com/p/c79b65b253fa Spring boot配置多个Redis数据源操作实例 在SpringBoot是项目中整合了两个Redis的操作实例 ...
- Java中Jedis操作Redis与Spring的整合
Redis是一个key-value存储系统.它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合).这些数据类型都支持push/pop. ...
- Spring Boot 2.x整合Redis
最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助. Redis是什么 Redis 是开源免费高性能的key-value数据库.有以下的优势(源于Redis ...
- 7、Spring Boot 2.x 集成 Redis
1.7 Spring Boot 2.x 集成 Redis 简介 继续上篇的MyBatis操作,详细介绍在Spring Boot中使用RedisCacheManager作为缓存管理器,集成业务于一体. ...
- Spring Boot 2.x 整合 Redis最佳实践
一.前言 在前面的几篇文章中简单的总结了一下Redis相关的知识.本章主要讲解一下 Spring Boot 2.0 整合 Redis.Jedis 和 Lettuce 是 Java 操作 Redis 的 ...
- Spring Boot 多站点利用 Redis 实现 Session 共享
如何在不同站点(web服务进程)之间共享会话 Session 呢,原理很简单,就是把这个 Session 独立存储在一个地方,所有的站点都从这个地方读取 Session. 通常我们使用 Redis 来 ...
- Spring Boot 如何快速集成 Redis 哨兵?
上一篇:Spring Boot 如何快速集成 Redis? 前面的分享栈长介绍了如何使用 Spring Boot 快速集成 Redis,上一篇是单机版,也有粉丝留言说有没有 Redis Sentine ...
- Jedis操作Redis数据库
添加Maven依赖: <dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</grou ...
- Jedis操作Redis
Jedis操作Redis的常用封装方法 @Resource(name="jedispool") private JedisPool pool=null; /** * 设置缓存对象过 ...
- 四、Jedis操作Redis
前言: 原来我们操作mysql需要用的jdbc,现在操作redis则需要jedis,jedis是客户端,而redis是服务器,使用jedis客户端来操作redis. 在这里要使用jedis操作red ...
随机推荐
- JAVA第一周学习
新学期伊始,六门专业课,课课重要,无法抉择重心,但日子还是要过的,而且要精细的过,不能得过且过 JAVA第一周任务 一:学习第一章视频 二:使用JDB调试JAVA 三:输入调试教材上代码,并把代码上传 ...
- [物理学与PDEs]第5章习题7 各向同性材料时稳定性条件的等价条件
在线性弹性时, 证明各向同性材料, 稳定性条件 (5. 27) 等价于 Lam\'e 常数满足 $$\bex \mu>0,\quad \lm+\cfrac{2}{3}\mu>0. \ee ...
- 【搞事情】VS2015下的openGL初始化
环境:glfw+glew+visual studio 2015 原材料下载链接: glfw 下载 glew 下载 glm库 下载 cmake 下载 (我下载的时候有些官网戳不开(大概校园网问题)... ...
- 代码,python1
def main(): try: number1,number2=eval(input("please enter two number")) result=number1/num ...
- Notepad++ --v7.5.8 (64bit) 安装目录显示插件(Explorer)
https://blog.csdn.net/qq_24153697/article/details/83036761 最近想自己做一个小项目,用Notepad做IDE,但是发现已安装的Notepad没 ...
- C# 处理文件的压缩与解压
最近做了一个关于winform 程序更新下载的功能,大概思路是,程序检测到服务端系统版本号发生改变,系统需要更新:这时请求服务端更新地址,下载更新包到程序的根目录,更新包是一个压缩包,下载完后再把压缩 ...
- undefined reference to symbol 'pthread_create@@GLIBC_2.2.5' 的修改方法
在编译DSO代码的时候会如下这样的问题: 检查DSO,在程序中没有用到pthread,但是在编译的时候却出现此类问题.仔细想了想了一下,在程序中用到了C++11中的线程std::thread,个人猜测 ...
- Ch02 课堂作业
测试一:运行结果: 测试二:运行结果: 测试三:运行结果:
- EmbeddedSolrServer的使用与solor6.3.0的使用
1. 到solr官网下载对应版本的solr: https://lucene.apache.org/solr/ 我下载的是:6.3.0版本(需要JDK8),solr默认集成了jetty容器,而且在 ...
- Docker入门-docker-compose使用(二)
Docker Docker容器大行其道,直接通过 docker pull + 启动参数的方式运行比较麻烦, 可以通过docker-compose插件快速创建容器 1.安装docker-compose ...