import redis.clients.jedis.Jedis;import redis.clients.jedis.exceptions.JedisDataException;public class JedisService { private String id; private int num; public JedisService(String id,int num){ this.id=id; this.num=num; } //进行业务判断 public void service(){ Jedis jedis=new Jedis("127.0.0.1",6379); String value=jedis.get("uid:"+this.id); try{ //如果不存在则创建 if(value==null){ jedis.setex("uid:"+this.id,20,Long.MAX_VALUE-num+""); }else{ //存在则增加 Long incr = jedis.incr("uid:" + this.id); job(this.id,num-(Long.MAX_VALUE-incr)); } }catch (JedisDataException e){ System.out.println("您的次数已用尽,请升级会员"); } } //进行业务操作 public void job(String id,Long times){ System.out.println(id+"正在执行第"+times+"次操作"); }}class MyThread extends Thread{ JedisService jedisService; public MyThread(String id,int num){ jedisService=new JedisService(id,num); } public void run(){ while(true){ jedisService.service(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }}class Main{ public static void main(String[] args) { MyThread myThread1=new MyThread("初级用户",10); myThread1.start(); MyThread myThread2=new MyThread("高级用户",20); myThread2.start(); }}
利用redis实现服务调用次数控制
时间:2023-08-01
相关推荐