package com.roadshow.uds.redis;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class RedisConnection {
@Value(value = "${redis.host}")
private String host;
@Value(value = "${redis.port}")
private int port;
@Value(value = "${redis.password}")
private String password;
private RedisConnection(){}
private RedisConnection(Builder builder) {
this.host = builder.host;
this.password = builder.password;
this.port = builder.port;
}
public String getPassword() {
return password;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setPassword(String password) {
this.password = password;
}
static class Builder {
String host;
int port;
//optional
String password;
public Builder(String host, int port) {
this.host = host;
this.port = port;
}
public Builder withPassWord(String pwd) {
this.password = pwd;
return this;
}
public RedisConnection build() {
return new RedisConnection(this);
}
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RedisConnection that = (RedisConnection) o;
if (port != that.port)
return false;
return host != null ? host.equals(that.host) : that.host == null;
}
@Override public int hashCode() {
int result = host != null ? host.hashCode() : 0;
result = 31 * result + port;
return result;
}
}
package com.roadshow.uds.redis;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RedisClient {
private static Logger logger=LoggerFactory.getLogger(RedisClient.class);
private static final ConcurrentHashMap<RedisConnection, RedisClient> cache =
new ConcurrentHashMap<>();
@Autowired
private RedisConnection redisConnection;
private static Object lock = new Object();
private JedisPool pool;
public Jedis getJedis(){
return pool.getResource();
}
public RedisClient() {
}
@PostConstruct
public void init(){
pool = new JedisPool(new JedisPoolConfig(), redisConnection.getHost(), redisConnection.getPort(), 2000,
redisConnection.getPassword(), Protocol.DEFAULT_DATABASE);
}
public RedisClient(RedisConnection conn) {
this.redisConnection = conn;
pool = new JedisPool(new JedisPoolConfig(), conn.getHost(), conn.getPort(), 2000,
conn.getPassword(), Protocol.DEFAULT_DATABASE);
}
public static RedisClient instance(RedisConnection conn) {
RedisClient client = cache.get(conn);
if (client == null) {
synchronized (lock) {
client = new RedisClient(conn);
cache.putIfAbsent(conn, client);
}
}
return client;
}
public void set(String key, Object obj) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = Serializer.serializer(obj);
String code = jedis.set(key, value);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public void setString(String key, String obj) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set(key, obj);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public void set(final String key, final Object obj, final String nxxx, final String expx,
final long time) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = Serializer.serializer(obj);
String code = jedis.set(key, value, nxxx, expx, time);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public String getString(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = jedis.get(key);
return value;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public Object getObject(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = jedis.get(key);
if (value == null) {
return null;
}
return Serializer.deSerializer(value);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public void setObject(final String key, final Object obj,Integer expireTime) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = Serializer.serializer(obj);
String code = jedis.set(key, value);
if(expireTime!=null){
jedis.expire(key,expireTime);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public void set(String key, String obj,Integer expireTime) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String code = jedis.set(key, obj);
if(expireTime!=null){
jedis.expire(key,expireTime);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public void setjson(String key, Object obj,Integer expireTime) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = JSON.toJSONString(obj);
String code = jedis.set(key, value);
if(expireTime!=null){
jedis.expire(key,expireTime);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public String getjson(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = jedis.get(key);
if (value == null) {
return null;
}
return value;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public boolean del(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.del(key);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
return true;
}
public Boolean exists(final String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.exists(key);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public Long incr(final String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.incr(key);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
close(jedis);
}
}
public boolean setnx(String key, String value){
Jedis jedis = null;
try {
jedis = pool.getResource();
long res = jedis.setnx(key, value);
if(res==1){
return true;
}
return false;
} catch (Exception e) {
logger.error("redis lock error:"+key, e);
} finally {
close(jedis);
}
return false;
}
public List<String> blpop(int timeout,String... keys) {
Jedis jedis = null;
List<String> list = new ArrayList<String>();
try {
jedis = pool.getResource();
list = jedis.blpop(timeout, keys);
return list;
} catch (Exception e) {
logger.error("redis blpop error:"+keys,e);
}finally{
close(jedis);
}
return list;
}
public boolean rpush(String key,String... values) {
Jedis jedis = null;
try {
jedis = pool.getResource();
long resCode = jedis.rpush(key, values);
logger.debug("key:"+key+",rpush result:" + resCode);
return resCode>0;
} catch (Exception e) {
logger.error("redis rpush error:"+key,e);
}finally{
close(jedis);
}
return false;
}
private void close(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
public static String keyBuilder(String packageName,String className,String... args){
String keySplit = "_";
StringBuffer key = new StringBuffer("uds");
key.append(keySplit).append(packageName).append(keySplit).append(className);
for (String arg : args) {
key.append(keySplit).append(arg);
}
return key.toString();
}
}
package com.roadshow.uds.redis;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RedisLock {
private static Logger logger = LoggerFactory.getLogger(RedisLock.class);
public static int timeOut = 2*60;
private static String end = "_lock";
private static ThreadLocal<Integer> stateNum = new ThreadLocal<Integer>(){
public Integer initialValue() {
return 0;
}
};
private volatile int state;
private RedisClient rc;
private String lockKey;
public RedisLock(RedisClient rc, String lockKey) {
this.rc = rc;
this.lockKey = lockKey;
}
/**
* 加锁,锁this.lockKey
* 未获取到锁时阻塞当前线程
* @return 解锁用的标识符
*/
public String lock() {
String identifier = UUID.randomUUID().toString();
Thread current = Thread.currentThread();
state = stateNum.get();
int c = state;
if (c == 0) {
while(true){
if (!rc.setnx(lockKey, identifier)) {
logger.info("线程:" + current.getName() + " 未获取到锁:" + lockKey + ",继续等锁");
rc.blpop(timeOut, lockKey+end);
continue;
}else{
logger.info("线程:" + current.getName() + " 获取到锁:" + lockKey);
}
state = c + 1;
break;
}
}else{
state = c + 1;
identifier = rc.getString(lockKey);
}
stateNum.set(state);
return identifier;
}
/**
* 释放锁
* @param identifier 调用lock方法返回的标识符
* @return
*/
public boolean unlock(String identifier) {
state = stateNum.get();
int c = state - 1;
if (c < 0) // overflow
throw new Error("Maximum lock count exceeded");
String value = rc.getString(lockKey);
if(value==null||!identifier.equals(value)){
return false;
}
if(c==0){
rc.del(lockKey);
rc.rpush(lockKey+end, "release");
logger.info("线程:" + Thread.currentThread().getName() + " 释放锁:" + lockKey);
}
state = c;
stateNum.set(state);
return true;
}
public String toString() {
return "[lockKey:"+lockKey+",stateNum:"+state+"]";
}
}
package com.roadshow.uds.redis;
import org.apache.commons.codec.binary.Base64;
import org.nustaq.serialization.FSTConfiguration;
public class Serializer {
static ThreadLocal<FSTConfiguration> conf = new ThreadLocal() {
public FSTConfiguration initialValue() {
// return FSTConfiguration.createDefaultConfiguration();
return FSTConfiguration.createJsonConfiguration(false,false);
}
};
public static String serializer(Object obj) {
return Base64.encodeBase64String(serializerToBytes(obj));
}
public static byte[] serializerToBytes(Object obj) {
return conf.get().asByteArray(obj);
}
public static Object deSerializer(String obj) {
return conf.get().asObject(Base64.decodeBase64(obj));
}
}
测试
public class RedisClientTest {
private static RedisClient client;
@Before
public void init() {
RedisConnection conn =
new RedisConnection.Builder("你的ip", 6379).withPassWord("你的密码")
.build();
client = RedisClient.instance(conn);
}
@Test
public void testSet() throws Exception {
Person p = initP();
client.set("p1", p);
}
@Test
public void testGet() throws Exception {
Person p = (Person) client.get("p1");
System.out.println(p.getName());
}