1 Star 0 Fork 295

宁静致远 / spring-boot-demo

forked from Mrwen / spring-boot-demo 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ShardingTableKeyGenerator.java 1.53 KB
一键复制 编辑 原始数据 按行查看 历史
package com.example.config.sharding.key;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.example.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import java.util.Properties;
/**
* <p>
* sharding-jdbc自定义主键,这里使用redis进行自增操作
* </p>
*
* @author MrWen
**/
@Slf4j
public class ShardingTableKeyGenerator implements ShardingKeyGenerator {
private IRedisService redisService = null;
/**
* 自定义属性,看配置文件
*/
private Properties properties = new Properties();
private String redisKey;
/**
* 自定义主键生成器
*
* @return 自定义主键
*/
@Override
public Comparable<?> generateKey() {
if (redisService == null) {
redisService = SpringUtil.getBean(IRedisService.class);
}
if (StrUtil.isBlank(redisKey)) {
this.redisKey = properties.getProperty("redis-prfix");
}
//手动注入redisService
Long increment = redisService.increment(redisKey, 1L);
log.info("redisKey={},自增主键为{}", redisKey, increment);
return increment;
}
/**
* 声明类型
*/
@Override
public String getType() {
return "CUSTOM";
}
@Override
public Properties getProperties() {
return properties;
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/harry7/spring-boot-demo.git
git@gitee.com:harry7/spring-boot-demo.git
harry7
spring-boot-demo
spring-boot-demo
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891