优快云上目前最简单的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();
}
}
}
}
欢迎各位大佬指正!