背景:
有一个接口,用户传入包名列表,返回包名对应的游戏信息,可能存在恶意传入大量不存在的包名,导致跨过缓存直接查询数据库。
版本说明:
redis:4.0.14
spring-data-redis:1.7.11.RELEASE
redisson:3.2.0
项目中使用redis实现布隆过滤器的几种方式:
第一种:redis bloom 模块 + redisTemplate + lua 脚本
redis 安装布隆过滤器模块:
第1步:下载并编译布隆过滤器模块
cd /redisHome/redis # redis目录(使用自己的redis 目录)
git clone https://github.com/RedisLabsModules/redisbloom.git
cd redisbloom
make
第2步:redis 加载模块
有两种方法,
第一种:启动redis 时
redis-server --loadmodule /redisHome/redis/redisbloom/rebloom.so
第二种:redis 配置文件设置
loadmodule /redisHome/redis/redisbloom/rebloom.so
第3步:重启redis 服务器
使用redis-cli 测试布隆过滤器是否安装成功:
127.0.0.1:6379> bf.reserve testKey 0.01 1000000
具体的Quick Start 查看 redisbloom
接下来看下使用 redisTemplate+lua 来实现布隆过滤器的功能:
布隆过滤器的辅助类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class BloomFilterHelper {
@Autowired
private RedisTemplate redisTemplate;
// 初始化一个布隆过滤器
public Boolean tryInitBloomFilter(String key, long expectedInsertions, double falseProbability) {
Boolean keyExist = redisTemplate.hasKey(key);
if(keyExist) {
return false;
}
RedisScript<Boolean> script = new DefaultRedisScript<>(bloomInitLua(), Boolean.class);
RedisSerializer stringSerializer = redisTemplate.getStringSerializer();
redisTemplate.execute(script, stringSerializer, stringSerializer, Collections.singletonList(key), falseProbability+"", expectedInsertions+"");
return true;
}
// 添加元素
public Boolean addInBloomFilter(String key, Object arg) {
RedisScript<Boolean> script = new DefaultRedisScript<>(addInBloomLua(), Boolean.class);
return (Boolean) redisTemplate.execute(script, Collections.singletonList(key), arg);
}
// 批量添加元素
public Boolean batchAddInBloomFilter(String key, Object... args) {
RedisScript<Boolean> script = new DefaultRedisScript<>(batchAddInBloomLua(), Boolean.class);
return (Boolean) redisTemplate.execute(script, Collections.singletonList(key), args);
}
// 查看某个元素是否是存在
public Boolean existInBloomFilter(String key, Object arg) {
RedisScript<Boolean> script = new DefaultRedisScript<>(existInBloomLua(), Boolean.class);
return (Boolean) redisTemplate.execute(script, Collections.singletonList(key), arg);
}
// 批量查看元素是否存在
public List batchExistInBloomFilter(String key, Object... args) {
RedisScript<List> script = new DefaultRedisScript(batchExistInBloomLua(), List.class);
List<Long> results = (List) redisTemplate.execute(script, Collections.singletonList(key), args);
List<Boolean> booleanList = results.stream().map(res -> res == 1 ? true : false).collect(Collectors.toList());
return booleanList;
}
private String bloomInitLua() {
return "redis.call('bf.reserve', KEYS[1], ARGV[1], ARGV[2])";
}
private String addInBloomLua() {
return "return redis.call('bf.add', KEYS[1], ARGV[1])";
}
private String batchAddInBloomLua() {
StringBuilder sb = new StringBuilder();
sb.append("for index, arg in pairs(ARGV)").append("\r\n");
sb.append("do").append("\r\n");
sb.append("redis.call('bf.add', KEYS[1], arg)").append("\r\n");
sb.append("end").append("\r\n");
sb.append("return true");
return sb.toString();
}
private String existInBloomLua() {
return "return redis.call('bf.exists', KEYS[1], ARGV[1])";
}
private String batchExistInBloomLua() {
StringBuilder sb = new StringBuilder();
sb.append("local results = {}").append("\r\n");
sb.append("for index, arg in pairs(ARGV)").append("\r\n");
sb.append("do").append("\r\n");
sb.append("local exist = redis.call('bf.exists', KEYS[1], arg)").append("\r\n");
sb.append("table.insert(results, exist)").append("\r\n");
sb.append("end").append("\r\n");
sb.append("return results;");
return sb.toString();
}
}
由于项目中存在一个请求中需要查询多个游戏是否存在的业务场景,使用lua 脚本实现了布隆过滤器批量查询是否存在的操作,可以节省RRT(请求-响应时间)。
测试用例:
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hanhua.base.reader.BloomFilterHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.stream.Collectors;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext-*.xml"})
public class GameInfoTest {
@Autowired
private BloomFilterHelper bloomFilterHelper;
@Autowired
private GameInfoMapper gameInfoMapper;
@Test
public void testCreateBloom() {
Wrapper wrapper = new EntityWrapper<>();
wrapper.setSqlSelect("real_package_name");
List<GameInfo> games = gameInfoMapper.selectList(wrapper);
List<String> pckList = games.stream().map(game -> game.getRealPackageName()).collect(Collectors.toList());
Boolean tryInit = bloomFilterHelper.tryInitBloomFilter("bloom_exist_game_package", 100000, 0.01);
Boolean exc = bloomFilterHelper.batchAddInBloomFilter("bloom_exist_game_package", pckList.toArray());
System.out.println(tryInit);
System.out.println(exc);
}
@Test
public void testExistInBloom() {
System.out.println(bloomFilterHelper.existInBloomFilter("bloom_exist_game_package", "com.gdcompany.deepwaters"));
System.out.println(bloomFilterHelper.batchExistInBloomFilter("bloom_exist_game_package", "com.gdcompany.deepwaters",
"com.dena.a12026418", "com.activision.callofduty.codpbt", "com.Psyonix.RL2D11", "com.gyyx.ydxy"));
}
}
第二种:redis bloom 模块 + 修改redisTemplate 源码支持bloom 命令
安装布隆模块同上。
然后使用RedisTemplate 直接执行bloom 模块的相关命令:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext-*.xml"})
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testBfCommand() {
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
Boolean exist = redisTemplate.hasKey("bloom_exist_game_package_test");
if(!exist) {
//初始化一个布隆过滤器
connection.execute("bf_reserve", "bloom_exist_game_package_test".getBytes(), "0.01".getBytes(), "100000".getBytes());
}
//添加元素
System.out.println(connection.execute("bf_add", "bloom_exist_game_package_test".getBytes(), "com.seasun.shuangxiang.gp".getBytes()));
//查询元素是否存在
System.out.println(connection.execute("bf_exists", "bloom_exist_game_package_test".getBytes(), "com.seasun.shuangxiang.gp".getBytes()));
//批量添加元素
List addlist = redisTemplate.executePipelined((RedisCallback<Object>) conn -> {
conn.execute("bf_add", "bloom_exist_game_package_test".getBytes(), "com.migu.xxGame".getBytes());
conn.execute("bf_add", "bloom_exist_game_package_test".getBytes(), "com.mobilityware.Sudoku".getBytes());
conn.execute("bf_add", "bloom_exist_game_package_test".getBytes(), "com.issgamestudio.birdsup".getBytes());
return null;
});
System.out.println(JSON.toJSONString(addlist));
//批量查询是否存在
List existlist = redisTemplate.executePipelined((RedisCallback<Object>) conn -> {
conn.execute("bf_exists", "bloom_exist_game_package_test".getBytes(), "com.issgamestudio.birdsup".getBytes());
conn.execute("bf_exists", "bloom_exist_game_package_test".getBytes(), "com.migu.xxGame".getBytes());
conn.execute("bf_exists", "bloom_exist_game_package_test".getBytes(), "com.seasun.shuangxiang.gp".getBytes());
conn.execute("bf_exists", "bloom_exist_game_package_test".getBytes(), "com.test".getBytes());
return null;
});
System.out.println(JSON.toJSONString(existlist));
}
}
如果我们直接以上执行的话,必定会报错:
org.springframework.data.redis.RedisSystemException: Unknown redis exception; nested exception is java.lang.IllegalArgumentException: No enum constant redis.clients.jedis.Protocol.Command.BF_ADD
at org.springframework.data.redis.FallbackExceptionTranslationStrategy.getFallback(FallbackExceptionTranslationStrategy.java:48)
at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:38)
at org.springframework.data.redis.connection.jedis.JedisConnection.convertJedisAccessException(JedisConnection.java:212)
at org.springframework.data.redis.connection.jedis.JedisConnection.execute(JedisConnection.java:252)
因为RedisTemplate 将redis 能支持的命令已经在 redis.clients.jedis.Protocol.Command 中写死了,我们要做的就是添加下bloom 模块新增的命令,并修改下命令的格式,将 ’ _ ’ 改成 ’ . ',因为java 关键字不能使用 ’ . ’ 号:
public static enum Command {
..., BF_RESERVE, BF_EXISTS, BF_ADD;
public final byte[] raw;
Command() {
String name = this.name();
if(name.contains("_")) {
name = name.replace("_", ".");
}
raw = SafeEncoder.encode(name);
}
}
当然,这种方式不优雅,需要修改源码,不推荐使用,但当我们要使用自定义的redis 命令时,可以作为一种参考思路。最好spring-data-redis 后续的版本可以增加注册自定义命令的功能(俺找时间去github 提个PR,^ ^)
第三种:使用redisson API ,原生支持布隆过滤器 RBloomFilter
@Test
public void testRedissonBloom() {
RBloomFilter<String> filter = redissonClient.getBloomFilter("exist_game_package_test");
filter.tryInit(100000, 0.001);
filter.add("com.tencent.elemental");
System.out.println(filter.contains("com.tencent.elemental"));
System.out.println(filter.contains("com.test"));
// 下面是使用lua 查询,但是不能跟 RBloomFilter 混合使用,
// 因为一个是redisson 自带的布隆过滤器器算法,一个是redis 的布隆模块自带的算法,算法不一致
RBatch batch = redissonClient.createBatch();
RScriptAsync script = batch.getScript();
script.evalAsync(RScript.Mode.READ_ONLY, "redis.call('bf.exists', KEYS[1], ARGV[1])", RScript.ReturnType.BOOLEAN, Collections.singletonList("{exist_game_package_test}:config"), "com.seasun.shuangxiang.gp");
script.evalAsync(RScript.Mode.READ_ONLY, "redis.call('bf.exists', KEYS[1], ARGV[1])", RScript.ReturnType.BOOLEAN, Collections.singletonList("{exist_game_package_test}:config"), "com.test");
script.evalAsync(RScript.Mode.READ_ONLY, "redis.call('bf.exists', KEYS[1], ARGV[1])", RScript.ReturnType.BOOLEAN, Collections.singletonList("{exist_game_package_test}:config"), "com.tencent.elemental");
List<?> execute = batch.execute();
System.out.println(execute);
}
如果没有设计批量操作的话,尽量使用RBloomFilter,如果存在批量操作,目前RBloomFilter 不支持,需要自己使用lua 脚本实现,但是千万千万不要跟RBloomFilter 混搭,比如一个场景中使用RBloomFilter.add(),另一个场景中使用lua 脚本批量操作。