Java的Redis客户端Jedis:
Jedis jedis = new Jedis("127.0.0.1",6379);
//key
Set keys = jedis.keys("*");
//String
jedis.set("k4","k4_Redis");
//List
List list = jedis.lrange("mylist",0,-1);
//set
jedis.sadd("orders","jd001");
jedis.sadd("orders","jd002");
jedis.sadd("orders","jd003");
Set set1 = jedis.smembers("orders");
//hash
jedis.hset("hash1","userName","lisi");
System.out.println(jedis.hget("hash1","userName"));
Map map = new HashMap();
map.put("telphone","13810169999");
map.put("address","atguigu");
map.put("email","[email protected]");
jedis.hmset("hash2",map);
List result = jedis.hmget("hash2", "telphone","email");
//zset
jedis.zadd("zset01",60d,"v1");
jedis.zadd("zset01",70d,"v2");
jedis.zadd("zset01",80d,"v3");
jedis.zadd("zset01",90d,"v4");
Set s1 = jedis.zrange("zset01",0,-1);
链接池:
public class JedisPoolUtil {
private static volatile JedisPool jedisPool = null;
//被volatile修饰的变量不会被本地线程缓存,对该变量的读写都是直接操作共享内存。
private JedisPoolUtil() {}
public static JedisPool getJedisPoolInstance(){
if(null == jedisPool) {
synchronized (JedisPoolUtil.class){if(null == jedisPool) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxActive(1000);
poolConfig.setMaxIdle(32);
poolConfig.setMaxWait(100*1000);
poolConfig.setTestOnBorrow(true);
jedisPool = new JedisPool(poolConfig,"127.0.0.1");
}
}
}
return jedisPool;
}
链接池—释放方法:
public static void release(JedisPool jedisPool,Jedis jedis)
{
if(null != jedis)
{
jedisPool.returnResourceObject(jedis);
}
}
链接池--主函数:
public class Test01 {
public static void main(String[] args) {
JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set("k18","v183");
} catch (Exception e) {
e.printStackTrace();
}finally{
JedisPoolUtil.release(jedisPool, jedis);
}
}
}
链接池参数:
Redis事务--秒杀案例:
1、解决计数器和人员记录的原子操作
2、利用乐观锁淘汰用户,解决超卖问题。
jsp:
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userid =request.getParameter("userid");
String prodid =request.getParameter("prodid");
boolean if_success=Miaosha_Redis.do_miaosha(userid,prodid);
response.getWriter().print(if_success);
}
Redis:
public static boolean do_miaosha(String uid,String prodid){
Jedis jedis = new Jedis "127.0.0.1",6379);
System.out.println("connection is OK==========>: "+jedis.ping());
jedis.watch(prodid);
Integer num = Integer.parseInt(jedis.get(prodid));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(num.intValue()==0){
jedis.unwatch();
return false;
}else{
Transaction transaction = jedis.multi();
transaction.decr(prodid);
transaction.lpush(prodid+"-usr", uid);
List list=transaction.exec();
if(list==null){
System.out.println("秒杀失败");
}else{
System.out.println(uid+":秒杀成功");
}
jedis.close();
return true;
}
}