Jedis实现批量删除Key
long result = 0 ;
Jedis jedis = new Jedis ( "101.199.64.121" , 9009 ) ;
Set< String> set = jedis. keys ( "succ" + "*" ) ;
Iterator< String> it = set. iterator ( ) ;
int i = 0 ;
while ( it. hasNext ( ) ) {
String keyStr = it. next ( ) ;
System. out. println ( keyStr) ;
i++ ;
result += jedis. del ( keyStr) ;
}
System. err. println ( i) ;
Jedis切换数据库并创建文件夹
Jedis jedis = new Jedis ( "101.199.64.121" , 9009 ) ;
String select = jedis. select ( 15 ) ;
System. err. println ( "select" + select) ;
jedis. set ( "demo:test1" , "1" ) ;
jedis. set ( "demo:test2" , "2" ) ;
jedis. set ( "demo:test3" , "3" ) ;
jedis. set ( "demo:test4" , "4" ) ;
jedis. set ( "demo:test5" , "5" ) ;
jedis. close ( ) ;
Jedis+redis实现抢票秒杀功能
public static void main ( String[ ] args) {
final String watchkeys = "watchkeys" ;
ExecutorService executor = Executors. newFixedThreadPool ( 20 ) ;
final Jedis jedis = new Jedis ( "101.199.64.121" , 9009 ) ;
jedis. set ( watchkeys, "100" ) ;
jedis. close ( ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
executor. execute ( new MyRunnable ( "user" + getRandomString ( 6 ) ) ) ;
}
executor. shutdown ( ) ;
}
public static String getRandomString ( int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789" ;
Random random = new Random ( ) ;
StringBuffer sb = new StringBuffer ( ) ;
for ( int i = 0 ; i < length; i++ ) {
int number = random. nextInt ( base. length ( ) ) ;
sb. append ( base. charAt ( number) ) ;
}
return sb. toString ( ) ;
}
创建线程类:
public class MyRunnable implements Runnable {
String watchkeys = "watchkeys" ;
Jedis jedis = new Jedis ( "101.199.64.121" , 9009 ) ;
String userinfo;
public MyRunnable ( ) {
}
public MyRunnable ( String uinfo) {
this . userinfo= uinfo;
}
@Override
public void run ( ) {
try {
jedis. watch ( watchkeys) ;
String val = jedis. get ( watchkeys) ;
int valint = Integer. valueOf ( val) ;
if ( valint <= 100 && valint>= 1 ) {
Transaction tx = jedis. multi ( ) ;
tx. incrBy ( "watchkeys" , - 1 ) ;
List< Object> list = tx. exec ( ) ;
if ( list == null || list. size ( ) == 0 ) {
String failuserifo = "fail" + userinfo;
String failinfo= "用户:" + failuserifo + "商品争抢失败,抢购失败" ;
System. out. println ( failinfo) ;
} else {
for ( Object succ : list) {
String succuserifo = "succ" + succ. toString ( ) + userinfo ;
String succinfo= "用户:" + succuserifo + "抢购成功,当前抢购成功人数:"
+ ( 1 - ( valint- 100 ) ) ;
System. out. println ( succinfo) ;
}
}
} else {
String failuserifo = "kcfail" + userinfo;
String failinfo1= "用户:" + failuserifo + "商品被抢购完毕,抢购失败" ;
System. out. println ( failinfo1) ;
return ;
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
jedis. close ( ) ;
}
}