惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
CERT Recently Published Vulnerability Notes
U
Unit 42
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Securelist
L
Lohrmann on Cybersecurity
Blog — PlanetScale
Blog — PlanetScale
Recorded Future
Recorded Future
D
DataBreaches.Net
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
I
Intezer
P
Palo Alto Networks Blog
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
I
InfoQ
宝玉的分享
宝玉的分享
Security Latest
Security Latest
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Threatpost
Cisco Talos Blog
Cisco Talos Blog
P
Proofpoint News Feed
博客园 - 司徒正美
H
Hacker News: Front Page
Y
Y Combinator Blog
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
NISL@THU
NISL@THU
月光博客
月光博客
有赞技术团队
有赞技术团队
Cloudbric
Cloudbric
酷 壳 – CoolShell
酷 壳 – CoolShell
G
Google Developers Blog
A
Arctic Wolf
博客园 - 【当耐特】
W
WeLiveSecurity
V
Visual Studio Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
V
V2EX
C
Cyber Attacks, Cyber Crime and Cyber Security
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
Stack Overflow Blog
Stack Overflow Blog

CAYZLH

MacBook上备忘录APP的快捷键和手势 让Google屏蔽某些搜索结果 WSL自定义安装Ubuntu typora自动上传图片配置 自建giscus服务 Windows下结束指定端口的进程 批量修改maven多模块版本号 使用winsw部署SpringBoot项目 Gson简易指南 docker搭建Consul集群 使用Docker部署SpringBoot项目 Docker使用redis镜像 Docker使用rabbitmq Docker使用zookeeper Docker使用MySQL Dockerfile常用指令 Docker免sudo操作 雷鸟电视去广告 使用ADB卸载MIUI系统应用 利用GitHub做图床 将网站变成灰色 Github上传大文件 Android远程调试命令adb vscode快捷键的使用 SpringBoot文件上传异常处理 SpringBoot自动部署脚本 使用Spring读取文件的几种方式 Spring统一异常返回 利用Github做Maven私服 Redis常用指令 Maven常用指令 使用mysqldump导出数据 SpringBoot动态切换多数据源 Java8的日期处理实践 lambda表达式语法 Stream表达式语法 使用Optional优雅地判空 Android Support vs AndroidX 「Vue」Runtime-Complier和Runtime-only的区别 RecyclerView使用记录 动态设置布局之LayoutInflater Redis分布式锁的几种方案 打造一个舒服的写作环境(Hexo) 深入了解与使用ThreadLocal Maven中dependencyManagement的作用 Redis配置认证密码 nginx简单配置示例 Linux(macOS)换源 Linux搭建Git服务器 Linux配置ssh使用公钥登录远程服务器 Linux下find与exec的使用 Linux排查Java问题工具单 Linux常用命令 MySql数据库优化细节 API签名验证方案 Java集合框架 Redis基础知识总结 Spring事务管理 Redis为什么这么快 SpringBoot实现Jwt单点登录 SpringBoot实现Redis分布式锁 Spring面向切面编程(知识梳理) SpringBoot异步请求和异步调用 Mybatis中用到的几种设计模式 Docker Swarm RocketMQ相关流程图/原理图 SonarQube的安装与使用 宝塔面板部署vue项目 Tomcat的三种接收请求处理方式 Docker知识扫盲 安装Jenkins并用于部署SpringBoot项目 Tomcat单机多实例部署 Maven中Scope的分类 Springboot集成Shiro(前后端分离) Linux搭建frp服务(内网穿透) Redis高逼格指令 Docker私有仓库的搭建与使用 Dockerfile使用介绍 Redis的使用场景 Docker的网络模式
SpringBoot封装JedisUtils工具类
Ant丶 · 2022-10-25 · via CAYZLH

SpringBoot已经实现了很多实用的缓存组件;但是由于工作中习惯了试用JedisUtils工具类来进行缓存操作, 这里记录一下SpringBoot中对于JedisUtils的封装

操作

新建一个SpringBoot项目

修改pom.xml增加:


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>

新建JedisConfiguration.java用于配置JedisPool Bean

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
public class JedisConfiguration {

@Value("${spring.redis.host}")
private String host;

@Value("${spring.redis.port}")
private int port;

@Value("${spring.redis.timeout}")
private String timeouts;

@Value("${spring.redis.jedis.pool.min-idle}")
private int maxIdle;

@Value("${spring.redis.jedis.pool.max-wait}")
private String maxWaitMilliss;

@Value("${spring.redis.password}")
private String password;

@Bean(name = "jedisPool")
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
long maxWaitMillis = Long.parseLong(maxWaitMilliss.replace("ms", ""));
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
int timeout = Integer.parseInt(timeouts.replace("ms", ""));
return new JedisPool(jedisPoolConfig, host, port, timeout);
}

}

创建JedisUtils.java

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Set;

public class JedisUtils implements ApplicationContextAware {

private static ApplicationContext applicationContext = null;

private static JedisPool jedisPool = null;

private static volatile Jedis jedis = null;

private static Logger logger = Logger.getLogger("JedisUtils");

public JedisUtils() {
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (JedisUtils.applicationContext == null) {

JedisUtils.applicationContext = applicationContext;
}
}

public static Jedis getJedis() {
if (jedis == null) {
synchronized (Jedis.class) {
if (jedis == null) {
jedis = getJedisPool().getResource();
}
}
}
return jedis;
}

public static JedisPool getJedisPool() {
if (jedisPool == null) {
synchronized (JedisPool.class) {
if (jedisPool == null) {
jedisPool = applicationContext.getBean("jedisPool", JedisPool.class);
}
}
}
return jedisPool;
}







public static boolean hasKey(String key) {
return getJedis().exists(key);
}








public static boolean set(String key, String value) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getJedis();
result = "OK".equals(jedis.set(key, value));
} catch (Exception e) {
closeBrokenJedis(jedis);
logger.error("JedisCache.set falid", e);
}
return result;
}









public static boolean set(String key, String value, int timeOut) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getJedis();
result = "OK".equals(jedis.setex(key, timeOut, value));
} catch (Exception e) {
closeBrokenJedis(jedis);
logger.error("JedisCache.set falid", e);
}
return result;
}







public static String get(String key) {
String result = null;
Jedis jedis = null;
try {
jedis = getJedis();
result = jedis.get(key);
closeJedis(jedis);
} catch (Exception e) {
closeBrokenJedis(jedis);
logger.error("JedisCache.get falid", e);
}
return result;
}






public static void del(String key) {
getJedis().del(key);
}
}

其中的getJedisPool()可以从bean获取JedisPool对象, 用于后续的操作, 上面给出了部分代码, 完整版在这.

在springboot的主类上添加注解

@SpringBootApplication
@EnableCaching
@Import({JedisUtils.class, JedisPool.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}