基于 Sass 的架构之 redis 多租户
作者:智慧源点
- 2024-03-10 北京
本文字数:1321 字
阅读完需:约 4 分钟
redis 多租户相对来说比较简单,有一种简单的实现方案是在 key 前缀加上租户 id,关键代码如下:
@Bean
public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lqlcfactory) {
/**
* 为了给redis加执行效率埋点,集成了原本的StringRedisTemplate,重写了方法
*/
StringRedisTemplate redisTemplate = new MonitorStringRedisTemplate();
if ("true".equals(enablePartner)) {
log.info("[EnablePartnerInterceptor]启用redis多合作方拦截插件");
redisTemplate.setKeySerializer(new PartnerStringRedisSerializer(mode));
} else {
redisTemplate.setKeySerializer(new StringRedisSerializer());
}
lqlcfactory.setShareNativeConnection(false);
redisTemplate.setConnectionFactory(lqlcfactory);
return redisTemplate;
}
/**
* 通用RedisTemplate 基于jackson
*
* @param lqlcfactory
* @param redisTemplate
* @return
*/
private RedisTemplate<String, V> buildRedisTemplate(LettuceConnectionFactory lqlcfactory,
RedisTemplate<String, V> redisTemplate) {
lqlcfactory.setShareNativeConnection(false);
redisTemplate.setConnectionFactory(lqlcfactory);
// 设置value的序列化规则和 key的序列化规则
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = buildJackson2JsonRedisSerializer();
if ("true".equals(enablePartner)) {
log.info("[EnablePartnerInterceptor]启用redis多合作方拦截插件");
redisTemplate.setKeySerializer(new PartnerStringRedisSerializer(mode));
} else {
redisTemplate.setKeySerializer(new StringRedisSerializer());
}
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
log.info("[REDIS_INIT] redis初始化完成");
return redisTemplate;
}
@Slf4j
public class PartnerStringRedisSerializer extends StringRedisSerializer {
private String mode;
/**
*
*/
public PartnerStringRedisSerializer(String mode) {
super();
this.mode = mode;
}
@Override
public String deserialize(byte[] bytes) {
return RedisUtil.getKeyPrefix(super.deserialize(bytes));
}
@Override
public byte[] serialize(String string) {
return super.serialize(RedisUtil.getKeyPrefix(string));
}
}
public class RedisUtil {
/**
* 获取key统一前缀
*
* @return
*/
public static String getKeyPrefix(String key) {
if (EwpThreadLocal.isIgnorePartner() || !EwpThreadLocal.isEnablePartner()) {
return key;
} else {
return EwpThreadLocal.getPartnerCodeNotNull() + ":" + key;
}
}
}
复制代码
学习资料分享:极客时间、图灵、Python、AI 等,微信联系:wytwhdwdd
划线
评论
复制
发布于: 刚刚阅读数: 3
智慧源点
关注
终身学习、研究java架构、ai大模型 2019-12-06 加入
商业合作: wytwhdwdd
评论