Redis之Jedis
Jedis是可以使 java、PHP 与Redis连接的。
我们先准备jedis需要的东西:
jar的导入
下载地址:https://mvnrepository.com/artifact/redis.clients/jedis
基于maven
pom.xml配置
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
开始连接客户端
//连接Redis
Jedis j = new Jedis("localhost",6379);
//进行操作
j.set("name","mohan");
System.out.println(j.get("name"));
//关闭连接
j.close();;
Jedis读写redis数据
public class Demo1 {
private int count;
private String id;
public Demo1(String id,int count) {
this.id = id;
this.count = count;
}
public void service() {
Jedis jedis = JedisUtil.getJedis();
String value = jedis.get("compid"+id);
try {
if (value == null) {
jedis.setex("compid" + id, 15, Long.MAX_VALUE - count + "");
} else {
Long num = jedis.incr("compid" + id);
business(id, count - (Long.MAX_VALUE - num));
}
} catch (JedisDataException e) {
System.out.println("使用次数上线请升级为会员");
return;
} finally {
jedis.close();
}
}
public void business(String id ,long num ){
System.out.println(id+"业务执行了"+":"+num+"次");
}
}
class MyThread extends Thread{
Demo1 demo;
public MyThread(String id,int count){
demo = new Demo1(id,count);
}
public void run(){
while (true){
demo.service();
try {
Random r = new Random();
Thread.sleep(1000+ r.nextInt(200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Main{
public static void main(String [] args){
MyThread mt1 = new MyThread("普通用户",10);
MyThread mt2 = new MyThread("普通会员",30);
mt1.start();
mt2.start();
}
}
配置文件
工具类
public class JedisUtil {
private static JedisPool jedisPool = null;
private static String host = null;
private static int port;
private static int maxTotal;
private static int maxIdle;
static{
//读取配置文件 获得参数值
ResourceBundle rb = ResourceBundle.getBundle("jedis");
host = rb.getString("jedis.host");
port = Integer.parseInt(rb.getString("jedis.port"));
maxTotal = Integer.parseInt(rb.getString("jedis.maxTotal"));
maxIdle = Integer.parseInt(rb.getString("jedis.maxIdle"));
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
jedisPool = new JedisPool(poolConfig,host,port);
}
public static Jedis getJedis(){
return jedisPool.getResource();
}
public static void main(String [] args){
JedisUtil.getJedis();
}
}