1. Prepare the jar package
compile group: 'redis.clients', name: 'jedis', version: '2.8.1'
compile group: 'org.apache.commons', name: 'commons-pool2', version: '2.4.2'
2. Create a connection pool:
package com.aebiz.redis;
import com.aebiz.bas.util.ftp.FtpResource;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public final class RedisUtil {
// //Redis server IP
private static String ADDR = "192.168.1.24";
//
// //Redis port number
private static int PORT = 6379;
//Access password
private static String AUTH = "admin";
//The maximum number of available connection instances, the default value is 8;
//If the value is -1, it means there is no limit; if the pool has allocated maxActive jedis instances, the state of the pool is exhausted at this time.
private static int MAX_ACTIVE = 200;
//Control the maximum number of jedis instances in idle (idle) status in a pool, the default value is also 8.
private static int MAX_IDLE = 50;
//The maximum time to wait for an available connection, in milliseconds, the default value is -1, which means never timeout. If the waiting time is exceeded, JedisConnectionException is thrown directly;
private static int MAX_WAIT = 10000;
private static int TIMEOUT = 10000;
//When borrowing a jedis instance, whether to perform the validate operation in advance; if it is true, the obtained jedis instance is available;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
/**
* Initialize the Redis connection pool
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
//Maximum number of idle connections
config.setMaxIdle(MAX_IDLE);
config.setMaxTotal(MAX_ACTIVE);
// config.setMaxWait(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
// config.setTestOnBorrow(false);
// config.setTestOnReturn(false);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
} catch (Exception e) {
e.printStackTrace ();
}
}
/**
* Get the Jedis instance
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
//reconnect
repeatConn();
Jedis resource = jedisPool.getResource();
return resource;
}
} catch (Exception e) {
e.printStackTrace ();
return null;
}
}
/**
* below redis 3.0
* Release jedis resources
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
//redis 3.0 and above
public static void backResource(final Jedis jedis) {
if (jedis != null && jedis.isConnected()) {
jedis.close();
}
}
public static void repeatConn(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(MAX_IDLE);
config.setMaxTotal(MAX_ACTIVE);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
}
}
3. Client encapsulation
package com.aebiz.redis;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.aebiz.auction.model.AuctionInfo;
import com.aebiz.pub.logs.PubLogs;
import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;
public class RedisClient {
private Jedis jedis;
public RedisClient() {
jedis = RedisUtil.getJedis();
}
public void close() {
if (null != jedis && jedis.isConnected()) {
jedis.close();
}
}
public long disLock(String key, String value) {
long result = 0;
StringBuffer lock = new StringBuffer();
result = jedis.setnx(key, value);
lock.append("key=").append(key);
lock.append(";lockstatus=").append(result);
// After acquiring the lock, set the lock expiration time
if (result > 0) {
// set lock for 30 seconds
long time = jedis.expire(key, 30);
lock.append(";lockTime=").append(time);
}
PubLogs.systemLogInfo(lock, null);
return result;
}
// remove lock
public long delLock(String key) {
StringBuffer lock = new StringBuffer(key);
lock.append(";delLock");
PubLogs.systemLogInfo(lock, null);
return jedis.del(key);
}
public List<AuctionInfo> getList(String key) {
List<String> list = jedis.lrange(key, 0, 1);
if (null != list && list.size() > 0) {
@SuppressWarnings("unchecked")
Collection<AuctionInfo> cc = JSONArray.toCollection(JSONArray.fromObject(list.get(0)), AuctionInfo.class);
ArrayList<AuctionInfo> ll = new ArrayList<AuctionInfo>(cc);
return ll;
// return JSONArray.toList(JSONArray.fromObject(list.get(0)),
// AuctionInfo.class);
}
return null;
}
public void setList(String key, List<AuctionInfo> list) {
StringBuffer sbf = new StringBuffer(key);
sbf.append("key=").append(key);
// Object to String
String strings = JSONArray.fromObject(list).toString();
sbf.append(";obj=").append(strings);
// clear cache
long del = jedis.del(key);
sbf.append(";delstatus=").append(del);
// put into cache
long len = jedis.rpush(key, strings);
sbf.append(";len=").append(len);
PubLogs.systemLogInfo(sbf, null);
}
// After simulating acquiring the lock, work
public void waitLock(String key) {
int times = 0;//Number of times to retry to acquire the lock
while (times < 10) {
long res = disLock(key, "lock");
if (res > 0) {
System.out.println("Processing business information");
times = 10;
delLock(key);
}else{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace ();
}
times++;
System.out.println("times---------------" + times);
}
}
System.out.println("-------------end=======");
}
//Simulate insert data, query data
public void test() {
long start = Calendar.getInstance().getTimeInMillis();
ExecutorService exe = Executors.newFixedThreadPool(80);
for (int j = 0; j < 20; j++) {
final int step = j;
exe.submit(new Runnable() {
@Override
public void run() {
RedisClient client = new RedisClient();
String key = "123456721ff";
List<AuctionInfo> list = new ArrayList<AuctionInfo>();
for (int i = 0; i < 6; i++) {
AuctionInfo auctionInfo = new AuctionInfo();
auctionInfo.setId("1" + i);
auctionInfo.setGoodsNo("goods" + i);
auctionInfo.setGoodsName("Goods Name" + i);
list.add(auctionInfo);
}
client.setList(key, list);
List<AuctionInfo> result = client.getList(key);
for (AuctionInfo item : result) {
System.out.print(item.getId() + "--" + item.getGoodsNo());
}
System.out.println("===" + step);
client.close();
}
});
}
exe.shutdown();
long end = Calendar.getInstance().getTimeInMillis();
System.out.println("time:" + (end - start));
}
public static void main(String[] args) {
for(int i=0;i<6;i++){
RedisClient client = new RedisClient();
client.waitLock("qwe123");
client.close();
System.out.println("=============================="+i);
}
}
}