每个数据库有自己的特性,基于redis数据库中SET集合类型的缓存,可以实现抽奖。
代码很简单,做个记录加深自己印象。
maven构建项目,引入
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
package com.example.demo.util;
import redis.clients.jedis.Jedis;
/**
*
* <p>Description: </p>
* @author
* @date 2020-8-9
* @version 1.0
*/
public class RedisByJedisUtils {
private String ip = "192.168.208.128";
private int port = 6379;
public void set(String key, String value) {
Jedis jedis = new Jedis(ip, port);
jedis.auth("foobared");
System.out.println(jedis.set(key, value));
jedis.close();
}
public boolean exists(String key) {
Jedis jedis = new Jedis(ip, port);
jedis.auth("foobared");
boolean existBoolean = jedis.exists(key);
jedis.close();
System.out.println(existBoolean);
return existBoolean;
}
public String getType(String key) {
Jedis jedis = new Jedis(ip, port);
jedis.auth("foobared");
String keyType = jedis.type(key);
jedis.close();
System.out.println(keyType);
return keyType;
}
public void sadd(String key, String value) {
Jedis jedis = new Jedis(ip, port);
jedis.auth("foobared");
System.out.println(jedis.sadd(key, value));
jedis.close();
}
public String spop(String key) {
Jedis jedis = new Jedis(ip, port);
jedis.auth("foobared");
String value = jedis.spop(key);
jedis.close();
return value;
}
/**
* 抽奖demo
*/
public void luckDraw() {
System.out.println("抽奖号码为:");
for(int i = 0; i < 10; i++) {
System.out.print(spop("luckdraw") + " ");
}
}
/**
* 初始化抽奖数据
*/
public void init() {
for(int i = 0; i < 100; i++) {
sadd("luckdraw", i+"");
}
}
public static void main(String[] args) {
//new RedisByJedisUtils().init();
new RedisByJedisUtils().luckDraw();
}
}