Package Com.test.util.redis;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;
Import Redis.clients.jedis.JedisPoolConfig;
public class Redisutil implements Runnable {
Private Jedispool pool = null;
public volatile int count=0;
/**
* @ Function: constructor with parameters
* @ parameter: Host, hostname or host IP
* @ Parameters: port, ports
* @ parameter: password, access password for Redis database
*/
Public Redisutil (string host, int port, string password) {
if (pool = = null) {
Jedispoolconfig config = new Jedispoolconfig ();
Controls how many Jedis instances a pool can allocate, obtained through Pool.getresource ();
If the assignment is-1, it is unrestricted, and if the pool is already assigned a maxtotal Jedis instance, the state of the pool is exhausted (exhausted) at this time.
Config.setmaxtotal (1);
Pool = new Jedispool (config, host, port, 60000, password);
}
}
/**
* @ function: Get the value from Redis key and release the connection resource
* @ parameter: Key, key value
* @ return: Successful return value, failure to return null
*/
public string get (string key) {
Jedis Jedis = null;
String value = null;
try {
Jedis = Pool.getresource ();
Value = Jedis.get (key);
} catch (Exception e) {
Pool.returnbrokenresource (Jedis);
E.printstacktrace ();
} finally {
if (null! = Pool) {
Pool.returnresource (Jedis);
}
}
return value;
}
/**
* @ Function: Deposit key and value to Redis (overwrite if key already exists), and release the connection resource
* @ parameter: Key, key
* @ parameter: value, which corresponds to key
* @ return: Successful return "OK", failed to return "0"
*/
public void Set (String key,string value) {
Jedis Jedis = null;
synchronized (this) {
try{
count=count+1;
Jedis = Pool.getresource ();
Jedis.set (key, Value+count);
System.out.println (Jedis.get (key));
} catch (Exception e) {
TODO auto-generated Catch block
Pool.returnbrokenresource (Jedis);
E.printstacktrace ();
}finally {
if (null! = Pool) {
Pool.returnresource (Jedis);
}
}
}
}
@Override
public void Run () {
System.out.println (Thread.CurrentThread ());
This.set ("foo", "Bar");
}
}
Test class:
Package Com.test.util.redis;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;
public class Jredis {
public static void Main (string[] args) {
String host = "localhost";
String password = null;
int port = 6379;
Redisutil redisutil = new Redisutil (host, port, password);
Executorservice Es=executors.newfixedthreadpool (5);
for (int i=0;i<20;i++) {
Es.execute (redisutil);
New Thread (Redisutil). Start ();
}
Es.shutdown ();
try {
Es.awaittermination (Timeunit.milliseconds);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Test over");
}
}
Redis concurrent processing, multithreading, and synchronized lock applications