CSDN上目前最简单的Redis封装使用
废话少说,直接代码(此次封装中包括了String和Hash中最常用的set,get,del)
首先导入2个Jar包,接下来的事情就简单了
commons-pool2-2.3.jar
jedis-2.7.0.jar
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;
//以上为导包内容
public class JedisUtils {
private static JedisPool pool;
//连接池的创建:放到静态代码里,一个应用里只要有一个连接池对象即可,用完即可释放
static {
/* 1.创建连接池的配置信息对象
配置文件中包含了4种必备要素
1. host ip地址
2. port 端口
3. maxTotal 最大连接数
4. maxidle 最大空闲连接
----->从src中读取配置文件(极简),可以有效的解决硬编码问题 */
ResourceBundle bundle = ResourceBundle.getBundle(\"jedis\");
String host = bundle.getString(\"host\");
int port = Integer.parseInt(bundle.getString(\"port\"));
int maxTotal = Integer.parseInt(bundle.getString(\"maxTotal\"));
int maxIdle = Integer.parseInt(bundle.getString(\"maxidle\"));
JedisPoolConfig Config = new JedisPoolConfig();
Config.setMaxTotal(maxTotal);
Config.setMaxIdle(maxIdle);
pool = new JedisPool(Config, host, port);
}
public static Jedis getJedis() {
return pool.getResource();
}
public static String get(String key) {
Jedis jedis = null;
String value = null;
try {
jedis = getJedis();
value = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return value;
}
public static void set(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.set(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static void del(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static void hset(String key, String field, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hset(key, field, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static String hget(String key, String field) {
Jedis jedis = null;
String value = null;
try {
jedis = getJedis();
value = jedis.hget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return value;
}
public static void hdel(String key, String field) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hdel(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
欢迎各位大佬指正!
继续阅读与本文标签相同的文章
上一篇 :
网红直播经济大热的背后,藏着你所看不清的黑暗……
下一篇 :
实习总结(ERwin的使用)2018年12月
-
服务器远程的安全管理办法
2026-05-18栏目: 教程
-
语音顶会Interspeech 论文解读|Investigation of Transformer based Spelling Correction Model for CTC-based End-to-End Mandarin Speech Recognition
2026-05-18栏目: 教程
-
阿里云“网红"运维工程师白金:做一个平凡的圆梦人 | 9月11号栖夜读
2026-05-18栏目: 教程
-
十位大师零距离,云栖大会通票+限量周边,还不够诱人吗亲? | 开发者必读(062期)
2026-05-18栏目: 教程
-
相同类中方法间调用时日志Aop失效处理
2026-05-18栏目: 教程
