Redis
1.配置Jedis参数
redis.clients.jedis.JedisPoolConfig
2.配置redis池
redis.clients.jedis.JedisPool
3.配置工具map
4.jedis的使用
文末会附上jedis工具类的java代码
5.服务器查看redis的键值
ps -ef | grep redis-server #查看redis信息
netstat -ano | grep -6379 #按端口查找
redis-cli -h 127.0.0.1 -p 6379 --raw #登陆redis服务器,-h 主机ip , -p 端口号 , -a 密码 --raw按中文原有方式输出
KEYS #返回所有关键字
GET key #根据关键字获取字符串类型的值
HEYS key #返回哈希表key中所有的域
HGET key field #返回哈希表key中给定域的值
HMGET key field[filed....] #返回哈希表key中给定的多个域的值
DEL key[key...] #删除给定的一个或多个key
Quit
*************************************************************华丽的分割线*************************************************************
Memcache
1.配置IO线程池
memcacheResource
${memcacheURL}
10
10
150
5000
600000
false
3000
2.配置客户端和包装类
memcacheResource
3.服务器查看缓存
get key[key...] #返回储存在键中的值
set key 0 900 9 #设置键值对 key键 flags 一般为0 exptime 缓存时效(秒)bytes 在缓存中存储的字节
memcache #设置存储的值 必须换行,且长度要跟设置的字节数一致,不然会报错CLIENT_ERROR bad data chunk
replace、append、prepend的语法跟set一致
stats #统计命令
Redis 和 memcache 比较
内存使用效率:用简单的key-value存储,memcache的效率更好,而如果redis使用Hash结构来存储key-value,则redis的效率要高于memcache
性能方面: 在小数据量存储时,redis要高于memcache;在超过100K的数据中,memcache的性能更优
另外: redis对复杂数据提供的支持更多,而memcache可以设置多个服务器
JedisUtil.java
@Component
public class JedisUtil {
private static final Logger LOGGER = Logger.getLogger(JedisUtil.class);
/**默认数据库*/
public static final int DB_DEFAULT = 0;
/**数据库缓存*/
public static final int DB_SQL = 1;
/**jedis连接池对象名前缀*/
public static final String JEDIS_POOL_PREFIX = "jedisPool";
@Autowired
private Map jedisPoolsMap;
/**
* 获取jedis对象
* @param database 数据库
* @return Jedis对象
*/
private Jedis getJedis(int database){
if(MapUtils.isEmpty(jedisPoolsMap)){
LOGGER.info("=============================注入连接池jedisPoolsMap失败=========================================");
}
return jedisPoolsMap.get(JEDIS_POOL_PREFIX+database).getResource();
}
/**
* 检测redis是否OK
* @return ok返回true
*/
public boolean isOK(){
Boolean bl = Boolean.FALSE;
Jedis jedis = getJedis(DB_DEFAULT);
if(!CommonUtils.isEmpty(jedis)){
bl = Boolean.TRUE;
}
jedis.close();
return bl;
}
/**
* 设置缓存
* @param database 数据库
* @param key 缓存KEY
* @param value 缓存值
* @return Status code reply
*/
public String set(int databse,String key,String value){
Jedis jedis = getJedis(databse);
String val = jedis.set(key, value);
jedis.close();
return val;
}
/**
* 设置缓存
* @param key 缓存KEY
* @param value 缓存值
* @return Status code reply
*/
public String set(String key,String value){
return set(DB_DEFAULT, key, value);
}
/**
* 设置缓存
* @param database 数据库
* @param key 缓存KEY
* @param value 缓存值
* @return Status code reply
*/
public String set(int databse,String key,Serializable value){
Jedis jedis = getJedis(databse);
String val = jedis.set(key.getBytes(), SerializableUtil.toByteArray(value));
jedis.close();
return val;
}
/**
* 设置缓存
* @param key 缓存KEY
* @param value 缓存值
* @return Status code reply
*/
public String set(String key,Serializable value){
return set(DB_DEFAULT, key, value);
}
/**
* 设置带有时间长度的缓存
* @param database 数据库
* @param key 缓存KEY
* @param value 缓存值
* @param time 缓存时间 ,毫秒
* @return Status code reply
*/
public String set(int database,String key,String value,long time){
Jedis jedis = getJedis(database);
String nxxx = "NX";
if(jedis.exists(key)){
nxxx = "XX";
}
String val = jedis.set(key, value,nxxx,"PX",time);
jedis.close();
return val;
}
/**
* 设置带有时间长度的缓存
* @param key 缓存KEY
* @param value 缓存值
* @param time 缓存时间 ,毫秒
* @return Status code reply
*/
public String set(String key,String value,long time){
return set(DB_DEFAULT, key, value, time);
}
/**
* 设置带有时间长度的缓存
* @param database 数据库
* @param key 缓存KEY
* @param value 缓存值
* @param time 缓存时间 ,毫秒
* @return Status code reply
*/
public String set(int database,String key,Serializable value,long time){
Jedis jedis = getJedis(database);
byte[] byteKey = SerializableUtil.toByteArray(key);
String nxxx = "NX";
if(jedis.exists(byteKey)){
nxxx = "XX";
}
byte[] nxxxByte = nxxx.getBytes();
byte[] epxxByte = "PX".getBytes();
String val = jedis.set(byteKey, SerializableUtil.toByteArray(value),nxxxByte,epxxByte,time);
jedis.close();
return val;
}
/**
* 设置带有时间长度的缓存
* @param key 缓存KEY
* @param value 缓存值
* @param time 缓存时间 ,毫秒
* @return Status code reply
*/
public String set(String key,Serializable value,long time){
return set(DB_DEFAULT, key, value, time);
}
/**
* 检查redis中是否包含key
* @param database 数据库
* @param key redis key
* @return true if key is exists
*/
public boolean containsKey(int database,String key){
Jedis jedis = getJedis(database);
boolean result = jedis.exists(key);
jedis.close();
return result;
}
/**
* 检查redis中是否包含key
* @param key redis key
* @return true if key is exists
*/
public boolean containsKey(String key){
return containsKey(DB_DEFAULT, key);
}
/**
* 调用Redis的LPUSH命令
* @param database 数据库
* @param key redis key
* @param val redis value
* @return true if key is exists
*/
public Long lpush(int database,String key,String... val){
Long ret = -1L;
Jedis jedis = getJedis(database);
ret = jedis.lpush(key, val);
jedis.close();
return ret;
}
/**
* 调用Redis的LPUSH命令
* @param key redis key
* @param val redis value
* @return true if key is exists
*/
public Long lpush(String key,String... val){
return lpush(DB_DEFAULT, key, val);
}
/**
* 调用Redis的hmset 将map保存到redis缓存中
* @param database 数据库
* @param key
* @param map
*/
public void hmset(int database,String key,Map map){
Jedis jedis = getJedis(database);
jedis.hmset(key, map);
jedis.close();
}
/**
* 调用Redis的hmset 将map保存到redis缓存中
* @param key
* @param map
*/
public void hmset(String key,Map map){
hmset(DB_DEFAULT, key, map);
}
/**
* 调用Redis的hmget 获取对应key保存map中存储的fields对应的数据
* @param key
* @param fields
* @return
*/
public List hmget(int database,String key,String... fields){
Jedis jedis = getJedis(database);
List list = jedis.hmget(key, fields);
jedis.close();
return list;
}
/**
* 调用Redis的hmget 获取对应key保存map中存储的fields对应的数据
* @param key
* @param fields
* @return
*/
public List hmget(String key,String... fields){
return hmget(DB_DEFAULT, key, fields);
}
/**
* 调用Redis的hmget 获取对应key保存map中存储的fields对应的数据
* @param database 数据库
* @param key 缓存的KEY
* @param cls 需要转换的对象
* @param fields map的key
* @return
*/
public List hmget(int database,String key,Class cls,String... fields){
Jedis jedis = getJedis(database);
List list = jedis.hmget(key, fields);
if(CollectionUtils.isNotEmpty(list) && !list.contains(null)){
String retStr = Joiner.on(",").join(list);
retStr = StringUtils.appendIfMissing(retStr, "]", "]");
retStr = StringUtils.prependIfMissing(retStr, "[", "[");
jedis.close();
return JSON.parseArray(retStr, cls);
}
jedis.close();
return null;
}
/**
* 调用Redis的hmget 获取对应key保存map中存储的fields对应的数据
* @param key 缓存的KEY
* @param cls 需要转换的对象
* @param fields map的key
* @return
*/
public List hmget(String key,Class cls,String... fields){
return hmget(DB_DEFAULT, key, cls, fields);
}
/**
* 调用Redis的hmget 获取对应key保存map中存储的fields对应的数据
* @param database 数据库
* @param key 缓存的KEY
* @param type 需要转换的对象
* @param fields map的key
* @return
*/
public List hmget(int database,String key,Type type,String... fields){
Jedis jedis = getJedis(database);
List list = jedis.hmget(key, fields);
if(CollectionUtils.isNotEmpty(list) && !list.contains(null)){
String retStr = Joiner.on(",").join(list);
retStr = StringUtils.appendIfMissing(retStr, "]", "]");
retStr = StringUtils.prependIfMissing(retStr, "[", "[");
jedis.close();
return JSON.parseObject(retStr, type);
}
jedis.close();
return null;
}
/**
* 调用Redis的hmget 获取对应key保存map中存储的fields对应的数据
* @param key 缓存的KEY
* @param type 需要转换的对象
* @param fields map的key
* @return
*/
public List hmget(String key,Type type,String... fields){
return hmget(DB_DEFAULT, key, type, fields);
}
/**
* 调用Redis的hmget 获取全部数据
* @param database 数据库
* @param key
* @return
*/
public Map hgetAll(int dababase,String key){
Jedis jedis = getJedis(dababase);
Map map = jedis.hgetAll(key);
jedis.close();
return map;
}
/**
* 调用Redis的hmget 获取全部数据
* @param key
* @return
*/
public Map hgetAll(String key){
return hgetAll(DB_DEFAULT, key);
}
/**
* 调用Redis的hmget 获取全部value数据
* @param key
* @return
*/
public List
MemCacheWrapper.java
/**
* 包装 {@link MemCachedClient},集中处理缓存错误不影响业务流程
*
*
*/
public class MemCacheWrapper
{
private static ServerLogger logger = new ServerLogger(MemCacheWrapper.class);
private MemCachedClient client;
/**
* 是否可写(默认为可写)
*/
private boolean writable = true;
private String[] servers;
public MemCacheWrapper(MemCachedClient client)
{
this.client = client;
try
{
com.whalin.MemCached.SockIOPool sockIOPool = BeanHolder.getBean("memcacheResource");
this.servers = sockIOPool.getServers();
String localIp = InetAddress.getLocalHost().getHostAddress();
boolean matched = false;
for (String server : this.servers)
{
//只有添加在里面的ip才会开启可写模式;
if (server.contains("localhost") || server.contains("127.0.0.1") || server.contains(localIp))
{
matched = true;
break;
}
}
this.writable = matched;
}
catch (Exception e)
{
logger.error("判断memcached是否可写失败!", e);
}
}
public Map getMulti(Class type, String... keys)
{
return getMap(type, keys);
}
@SuppressWarnings("unchecked")
private Map getMap(Class type, String... keys)
{
Map map = client.getMulti(keys);
if (map == null)
{
// 总是返回一个Map防止程序出现空指针异常
return new HashMap();
}
Iterator> it = map.entrySet().iterator();
while (it.hasNext())// 类型转换检查
{
Entry entry = it.next();
if (entry.getValue() == null)
{
continue;
}
entry.setValue(castAs(type, entry.getKey(), entry.getValue()));
if (entry.getValue() == null)
{
it.remove();
}
}
return (Map)map;
}
public T get(Class type, String key)
{
Object t = client.get(key);
return castAs(type, key, t);
}
@SuppressWarnings("unchecked")
public T[] getMultiArray(Class type, String... keys)
{
Object[] values = client.getMultiArray(keys);
if (values == null)
{
return (T[])Array.newInstance(type, 0);
}
T[] arr = (T[])Array.newInstance(type, values.length);
for (int i = 0; i < values.length; i++)
{
arr[i] = castAs(type, null, values[i]);
}
return arr;
}
/**
* 增加一个指定键的计数器+1
*
* @param key
* @return
*/
public long incr(String key)
{
return client.incr(key);
}
/**
* 增加一个指定键的计数器+value
*
* @param key
* @param value
* @return
*/
public long incr(String key, long value)
{
return client.incr(key, value);
}
public long decr(String key)
{
return client.decr(key);
}
public long decr(String key, long value)
{
return client.decr(key, value);
}
public boolean delete(String key)
{
return client.delete(key);
}
@SuppressWarnings("deprecation")
public boolean delete(String key, Date expiry)
{
return client.delete(key, expiry);
}
public boolean set(String key, Object value)
{
if (!writable)
{
return false;
}
if (value == null)
{
Throwable t = new Throwable("null value to cache TraceStack");
logger.error("set a null value to memcache with key[" + key + "] ,See follow invoke trace", t);
return false;
}
return client.set(key, value);
}
public boolean set(String key, Object value, Date expire)
{
if (!writable)
{
return false;
}
if (value == null)
{
Throwable t = new Throwable("null value to cache TraceStack");
logger.error("set a null value to memcache with key[" + key + "] ,See follow invoke trace", t);
return false;
}
return client.set(key, value, expire);
}
/**
* 执行stats命令,返回缓存的当前状态
*
* @return
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public Map> stats()
{
Map map = client.stats();
if (map == null)
{
return new HashMap>();
}
return map;
}
/**
* 在所有的Memcached服务端执行缓存清除动作
*
* Will return true only if succeeds in clearing all servers.
*
* @return success true/false
*/
public boolean flushAll()
{
return client.flushAll();
}
/**
* 在指定的Memcached服务端执行缓存清除动作 Will return true only if succeeds in clearing all servers. If pass in null, then will
* try to flush all servers.
*
* @param servers optional array of host(s) to flush (host:port)
* @return success true/false
*/
public boolean flushAll(String[] servers)
{
return client.flushAll(servers);
}
/**
* 进行类型转换同时处理转换异常
*
* @param type
* @param value
* @return
*/
private T castAs(Class type, String key, Object value)
{
if (value == null)
{
return null;
}
try
{
T t = type.cast(value);
return t;
}
catch (ClassCastException ignoreMe)
{
StringBuilder errMsg = new StringBuilder("+++ incorrect cache type[");
errMsg.append(value.getClass().getName())
.append("] with key[" + key + "], value [")
.append(value)
.append("]");
errMsg.append(",expect type [").append(type.getName()).append("]");
logger.error(errMsg, ignoreMe);
}
return null;
}
public boolean isWritable()
{
return writable;
}
public void setWritable(boolean writable)
{
this.writable = writable;
}
public String[] getServers()
{
return servers;
}
}