首页 > 代码库 > redis 并发处理,多线程以及synchronized锁的应用
redis 并发处理,多线程以及synchronized锁的应用
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;
/**
* @功能:带参数的构造函数
* @参数:host,主机名或主机IP
* @参数:port,端口
* @参数:password,访问Redis数据库的密码
*/
public RedisUtil(String host, int port, String password) {
if (pool == null) {
JedisPoolConfig config = new JedisPoolConfig();
// 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxTotal个jedis实例,则此时pool的状态为exhausted(耗尽)。
config.setMaxTotal(1);
pool = new JedisPool(config, host, port, 60000, password);
}
}
/**
* @功能:通过Redis的key获取值,并释放连接资源
* @参数:key,键值
* @返回: 成功返回value,失败返回null
*/
public String get(String key){
Jedis jedis = null;
String value = http://www.mamicode.com/null;
try {
jedis = pool.getResource();
value = http://www.mamicode.com/jedis.get(key);
} catch (Exception e) {
pool.returnBrokenResource(jedis);
e.printStackTrace();
} finally {
if(null != pool) {
pool.returnResource(jedis);
}
}
return value;
}
/**
* @功能:向redis存入key和value(如果key已经存在 则覆盖),并释放连接资源
* @参数:key,键
* @参数:value,与key对应的值
* @返回:成功返回“OK”,失败返回“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");
}
}
测试类:
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(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" test over");
}
}
redis 并发处理,多线程以及synchronized锁的应用