package com.yiidata.intergration.web.modules.sys.cache;
import com.primeton.damp.cache.serde.JdkSerializer;
import com.primeton.damp.cache.serde.Serializer;
import com.primeton.damp.cache.serde.StringSerializer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import java.io.Closeable;
import java.io.IOException;
import java.io.Serializable;
import java.util.Set;
/**
*
*
* Created by zhaopx.
* User: zhaopx
* Date: 2019/8/21
* Time: 18:55
*
*
*
* @author zhaopx
*/
public class Redised implements ICache, Closeable {
private static Logger logger = LoggerFactory.getLogger(Redised.class);
/**
* Redis 的 Java Client
*/
Jedis jedis;
/**
* redis db index
*/
private final int db;
/**
* KEY 序列化
*/
private final Serializer KEY_SERDE = new StringSerializer();
/**
* Redis Cache 序列化方式
*/
private final Serializer VALUE_SERDE = new JdkSerializer();
public Redised() {
this("localhost", 6379, 0);
}
public Redised(String host, int port){
this(host, port, 0);
}
public Redised(String host, int port, int db){
this(host, port, null, db);
}
public Redised(String host, int port, String password){
this(host, port, password, 0);
}
public Redised(String host, int port, String password, int db){
this.db = db;
jedis = new Jedis(host, port);
if(StringUtils.isNotBlank(password)) {
jedis.auth(password);
}
jedis.select(db);
}
@Override
public void add(String key, Serializable value) {
if(value == null) {
return;
}
jedis.set(KEY_SERDE.serialize(key), VALUE_SERDE.serialize(value));
}
@Override
public void add(String key, int exp, Serializable value) {
byte[] keybytes = KEY_SERDE.serialize(key);
jedis.set(keybytes, VALUE_SERDE.serialize(value));
jedis.expire(keybytes, exp);
}
@Override
public Serializable get(String key) {
if(key == null) {
return null;
}
byte[] bytes = jedis.get(KEY_SERDE.serialize(key));
if(bytes == null) {
return null;
}
return VALUE_SERDE.deserialize(bytes);
}
/**
* 移除某条缓存
* @param key 缓存的 KEY
* @return
*/
@Override
public Serializable remove(String key) {
if(key == null) {
return null;
}
logger.info("remove cache key: {}", key);
return jedis.del(KEY_SERDE.serialize(key));
}
@Override
public int removeByPrefix(String prefix) {
Set keys = jedis.keys(prefix+"*");
if(keys != null && keys.size() > 0) {
for (String key : keys) {
remove(key);
}
}
return keys == null ? 0 : keys.size();
}
@Override
public void clear() {
jedis.flushDB();
}
@Override
public int size() {
return jedis.dbSize().intValue();
}
@Override
public void close() throws IOException {
jedis.close();
}
@Override
public void shutdown() {
try {
close();
} catch (IOException e) {
}
}
}