您的位置:首页 > 数据库 > Redis

java鬼混笔记:redis 3、java下使用redis,自定义一个工具类RedisUtil

2017-12-05 20:08 471 查看
记记用java操作redis,我就直接写成一个工具使用,方法也就几个,做个demo,需要哪个再补补。目前是使用单个redis的,加上了连接池,后面再试试集群的redis和分布式的看看。。。上代码。。。

package com.example.demo.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public enum MyRedisUtils {

INSTANCE;

private JedisPool jedisPool;

private MyRedisUtils() {
// 连接池配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(10000);// 最大连接数
config.setMaxIdle(2000);// 最大空闲连接数
config.setMaxWaitMillis(1000 * 100);// 获取连接最大等等时间
config.setTestOnBorrow(true);// 获取连接的时检查有效性

String ip = "127.0.0.1";
int port = 6379;
String password = "123";
int timeout = 100000;// 连接超时时间
jedisPool = new JedisPool(config, ip, port, timeout, password);
}

public Jedis getJedis() {
Jedis jedis = jedisPool.getResource();
return jedis;
}

public String set(String key, String value) {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.set(key, value);
} catch (Exception e) {
e.printStackTrace();
return "-1";
} finally {
releaseResource(jedis);
}
}

/**
* 保存字符串,没有返回null
* @param key
* @return
*/
public String get(String key) {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
return "-1";
} finally {
releaseResource(jedis);
}
}

/**
* 拼接,返回拼接后的长度
* @param key 目标的key
* @param value 要接在后面的value
* @return
*/
public Long append(String key, String value) {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.append(key, value);
} catch (Exception e) {
e.printStackTrace();
return 0L;
} finally {
releaseResource(jedis);
}
}

/**
* 保存字符串并设置保存有效期,成功返回OK
* @param key
* @param value
* @param seconds
* @return
*/
public String setex(String key, String value, int seconds) {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.setex(key, seconds, value);
} catch (Exception e) {
e.printStackTrace();
return "0";
} finally {
releaseResource(jedis);
}
}

/**
* 清空当前库下的数据
* @return
*/
public String flushDB() {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.flushDB();
} catch (Exception e) {
e.printStackTrace();
return "0";
} finally {
releaseResource(jedis);
}
}

/**
* 判断Key是否存在
* @param key
* @return
*/
public Boolean exists(String key) {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.exists(key);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
releaseResource(jedis);
}
}

/**
* 判断多个Key是否存在,返回存在的数量
* @param keys
* @return
*/
public Long exists(String... keys) {

Jedis jedis = null;
try {
jedis = getJedis();
return jedis.exists(keys);
} catch (Exception e) {
e.printStackTrace();
return 0L;
} finally {
releaseResource(jedis);
}
}

// 等等。。。

public void releaseResource(Jedis jedis) {
if (jedis != null) {
jedis.close();// 资源回收
}
}
}


ok,先记这些先,后面再补上。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐