策略名称 | 含义解释 |
---|---|
noeviction | 不会驱逐任何key(生产的默认配置就是这个) |
allkeys-lru | 对所有的key使用LRU算法进行删除 (基本都是用这个,比较稳定的方案) |
volatile-lru | 对所有设置了过期时间的key使用LRU算法进行删除 |
allkeys-random | 对所有key随机删除 |
volatile-random | 对所有设置了过期时间的key随机删除 |
volatile-ttl | 删除马上要过期的key |
allkeys-lfu | 对所有key使用LFU算法进行删除 |
volatile-lfu | 对所有设置了过期时间的key使用LFU算法进行删除 |
首先肯定是用Redis,redis天生单线程高可用,可以无锁实现加锁的代码效果,其次红包数值存储应该用list数据结构(set不允许重复,但是红包金额能够重复),并且list的pop出栈操作自动是原子性的不需要加锁,其次需要存储用户的抢红包记录
可以用hash结构.最后如果这些需要持久化的话可以最后开启异步线程同步到MySQL或者消息队列.
import cn.hutool.core.util.IdUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
@RestController
public class RedPackageController {
public static final String RED_PACKAGE_KEY = "redpackage";
public static final String RED_PACKAGE_CONSUME_KEY = "redpackage:consume";
@Resource
private RedisTemplate<String, Object> redisTemplate;
@PostMapping("/sendRedPackage")
public String sendRedPackage(int totalMoney, int redPackageNumber) {
//拆分红包
Integer[] splitRedPackages = splitRedPackage(totalMoney, redPackageNumber);
String key = RED_PACKAGE_KEY + IdUtil.simpleUUID();
//不需要加锁,一个人发,也不需要原子性,所以可以分成两部分设置
redisTemplate.opsForList().leftPushAll(key, splitRedPackages);
redisTemplate.expire(key, 1, TimeUnit.SECONDS);
return "success";
}
@PostMapping("/robRedPackage")
public String robRedPackage(String redPackageKey, String userId) {
Object redPackage = redisTemplate.opsForHash().get(RED_PACKAGE_CONSUME_KEY + redPackageKey, userId);
if (redPackage != null) {
throw new RuntimeException("你已经抢过红包了,不允许重复抢");
}
Integer money = (Integer) redisTemplate.opsForList().leftPop(RED_PACKAGE_KEY + redPackageKey);
if (money == null) {
throw new RuntimeException("红包已经被抢完了");
}
redisTemplate.opsForHash().put(RED_PACKAGE_CONSUME_KEY + redPackageKey, userId, money);
//后续如果需要进行持久化存储可以开启异步线程进入MySQL或者进入MQ消息队列再进一步处理
return "success";
}
private Integer[] splitRedPackage(int totalMoney, int redPackageNumber) {
int useMoney = 0;
Integer[] redPackageNumbers = new Integer[redPackageNumber];
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < redPackageNumber; i++) {
if (i == redPackageNumber - 1) {
redPackageNumbers[i] = totalMoney - useMoney;
} else {
//二倍均值法进行计算,这样的值比较平均(忽略小数)
int avgMoney = ((totalMoney - useMoney) / (redPackageNumber - i)) * 2;
redPackageNumbers[i] = 1 + random.nextInt(avgMoney - 1);
}
useMoney = useMoney + redPackageNumbers[i];
}
return redPackageNumbers;
}
}
用新浪微博的短链接算法来生成对应的短链接地址字符串,然后存入redis的hash结构当中
import java.security.MessageDigest;
public class ShortUrlUtil {
// 可以自定义生成 MD5 加密字符传前的混合 KEY
private static final String key = "test";
// 要使用生成 URL 的字符
private static final String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
public static String[] shortUrl(String url) {
// 对传入网址进行 MD5 加密
String hex = md5ByHex(key + url);
String[] resUrl = new String[4];
for (int i = 0; i < 4; i++) {
// 把加密字符按照8个字节一组分为4段
String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 将他看为16进制串与 0x3FFFFFFF(30位1)进行位与运算,超过30位的忽略处理
// 这里需要使用 long 型来转换,因为 Integer.parseInt() 只能处理 31 位 , 首位为符号位 , 如果不用long ,则会越界
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
StringBuilder outChars = new StringBuilder();
for (int j = 0; j < 6; j++) {
// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
long index = 0x0000003D & lHexLong;
// 把取得的字符相加
outChars.append(chars[(int) index]);
// 每次循环按位右移 5 位
lHexLong = lHexLong >> 5;
}
// 把字符串存入对应索引的输出数组
resUrl[i] = outChars.toString();
}
return resUrl;
}
/**
* MD5加密(32位大写)
*/
public static String md5ByHex(String src) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = src.getBytes();
md.reset();
md.update(b);
byte[] hash = md.digest();
StringBuilder hs = new StringBuilder();
String stamp;
for (byte value : hash) {
stamp = Integer.toHexString(value & 0xFF);
if (stamp.length() == 1)
hs.append("0").append(stamp);
else {
hs.append(stamp);
}
}
return hs.toString().toUpperCase();
} catch (Exception e) {
return "";
}
}
}
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
@RestController
public class ShortUrlController {
public static final String SHORT_URL_KEY = "short:url";
@Resource
private HttpServletResponse response;
@Resource
private RedisTemplate<String, Object> redisTemplate;
@PostMapping(value = "/shortUrl/encode")
public String shortUrlEnCode(String longUrl) {
String[] keys = ShortUrlUtil.shortUrl(longUrl);
int i = ThreadLocalRandom.current().nextInt(4);
String shortUrlKey = keys[i];
redisTemplate.opsForHash().put(SHORT_URL_KEY, shortUrlKey, longUrl);
return "http://1270.0.1:5555/" + shortUrlKey;
}
@PostMapping("/shortUrl/decode")
public void shortUrlDecode(String shortUrlKey) throws IOException {
String longUrl = (String) redisTemplate.opsForHash().get(SHORT_URL_KEY, shortUrlKey);
response.sendRedirect(longUrl);
}
}