集成
- 依赖
leaf-boot-starter
- 设置 zookeeper 地址
- 开启
@EnableLeafServer
- 使用
SnowflakeService
获取分布式唯一ID
leaf:
snowflake:
enable: true
address: localhost
port: 2181
@EnableLeafServer
@SpringBootApplication
public class IDAPP {
public static void main(String[] args) {
SpringApplication.run(IDAPP.class, args);
}
}
@RestController
@RequestMapping("/id")
@RequiredArgsConstructor
public class IDController {
private final SnowflakeService snowflakeService;
@RequestMapping(path = "/nextId", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<Long> nextId() {
// snowflakeService 中并未使用这个参数,因此可以传空字符串
return ResponseEntity.ok(snowflakeService.getId("").getId());
}
}
测试
@Slf4j
@SpringBootTest
class LeafServiceTest {
@Autowired
private SnowflakeService snowflakeService;
@Test
void nextId() {
log.info("id: {}", snowflakeService.getId("").getId());
}
}
# 查看 zookeeper 节点
# 出现 [services, snowflake] 这两个节点说明部署成功
zkCli.sh -server localhost:2181
ls /
依赖
<dependencies>
<dependency>
<groupId>com.tencent.devops.leaf</groupId>
<artifactId>leaf-boot-starter</artifactId>
<version>1.0.2-RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
</dependencies>
zookeeper
注意时区和微服务保持一致
version: '3.8'
services:
zoo1:
image: zookeeper
hostname: zoo1
restart: unless-stopped
ports:
- "2181:2181"
volumes:
- ./data/zoo1:/data
environment:
ZOO_MY_ID: 1
ZOO_SERVERS: server.1=0.0.0.0:2888:3888;2181 server.2=zoo2:2888:3888;2181
TZ: Asia/Shanghai
zoo2:
image: zookeeper
hostname: zoo2
restart: unless-stopped
ports:
- "2182:2181"
volumes:
- ./data/zoo2:/data
environment:
ZOO_MY_ID: 2
ZOO_SERVERS: server.1=zoo1:2888:3888;2181 server.2=0.0.0.0:2888:3888;2181
TZ: Asia/Shanghai