Skip to content

Commit 5adf41c

Browse files
committed
新增Springboot整合Zookeeper示例
1 parent 19d9934 commit 5adf41c

File tree

9 files changed

+383
-0
lines changed

9 files changed

+383
-0
lines changed

Spring-Boot-Zookeeper/pom.xml

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>org.springframework.boot</groupId>
7+
<artifactId>spring-boot-starter-parent</artifactId>
8+
<version>2.2.6.RELEASE</version>
9+
<relativePath/> <!-- lookup parent from repository -->
10+
</parent>
11+
<groupId>com</groupId>
12+
<artifactId>springboot</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
<name>Spring-Boot-Zookeeper</name>
15+
<description>Demo project for Spring Boot</description>
16+
17+
<properties>
18+
<java.version>1.8</java.version>
19+
<curator.version>4.3.0</curator.version>
20+
</properties>
21+
22+
<dependencies>
23+
<dependency>
24+
<groupId>org.springframework.boot</groupId>
25+
<artifactId>spring-boot-starter-web</artifactId>
26+
</dependency>
27+
<dependency>
28+
<groupId>org.apache.curator</groupId>
29+
<artifactId>curator-framework</artifactId>
30+
<version>${curator.version}</version>
31+
</dependency>
32+
<dependency>
33+
<groupId>org.apache.curator</groupId>
34+
<artifactId>curator-recipes</artifactId>
35+
<version>${curator.version}</version>
36+
</dependency>
37+
<dependency>
38+
<groupId>org.apache.curator</groupId>
39+
<artifactId>curator-client</artifactId>
40+
<version>${curator.version}</version>
41+
</dependency>
42+
<dependency>
43+
<groupId>org.apache.commons</groupId>
44+
<artifactId>commons-lang3</artifactId>
45+
<version>3.10</version>
46+
</dependency>
47+
<dependency>
48+
<groupId>org.projectlombok</groupId>
49+
<artifactId>lombok</artifactId>
50+
<version>1.18.12</version>
51+
<scope>provided</scope>
52+
</dependency>
53+
<dependency>
54+
<groupId>org.springframework.boot</groupId>
55+
<artifactId>spring-boot-starter-test</artifactId>
56+
<scope>test</scope>
57+
<exclusions>
58+
<exclusion>
59+
<groupId>org.junit.vintage</groupId>
60+
<artifactId>junit-vintage-engine</artifactId>
61+
</exclusion>
62+
</exclusions>
63+
</dependency>
64+
</dependencies>
65+
66+
<build>
67+
<plugins>
68+
<plugin>
69+
<groupId>org.springframework.boot</groupId>
70+
<artifactId>spring-boot-maven-plugin</artifactId>
71+
</plugin>
72+
</plugins>
73+
</build>
74+
75+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.springboot;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringBootZookeeperApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringBootZookeeperApplication.class, args);
11+
}
12+
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.springboot.config;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import org.apache.curator.RetryPolicy;
5+
import org.apache.curator.framework.CuratorFramework;
6+
import org.apache.curator.framework.CuratorFrameworkFactory;
7+
import org.apache.curator.retry.ExponentialBackoffRetry;
8+
import org.springframework.context.annotation.Bean;
9+
import org.springframework.context.annotation.Configuration;
10+
11+
import javax.annotation.Resource;
12+
13+
/**
14+
* @author dengzhiming
15+
* @date 2020/5/5 14:06
16+
*/
17+
@Slf4j
18+
@Configuration
19+
public class ZookeeperConfig {
20+
21+
@Resource
22+
private ZookeeperProps zookeeperProps;
23+
24+
@Bean(value="zkClient",initMethod="start")
25+
public CuratorFramework curatorFramework(){
26+
//重试策略,初试时间1秒,重试10次
27+
RetryPolicy policy = new ExponentialBackoffRetry(
28+
zookeeperProps.getBaseSleepTimeMs(),
29+
zookeeperProps.getMaxRetries());
30+
//通过工厂创建Curator
31+
CuratorFramework client = CuratorFrameworkFactory.builder()
32+
.connectString(zookeeperProps.getServer())
33+
.authorization("digest",zookeeperProps.getDigest().getBytes())
34+
.connectionTimeoutMs(zookeeperProps.getConnectionTimeoutMs())
35+
.sessionTimeoutMs(zookeeperProps.getSessionTimeoutMs())
36+
.retryPolicy(policy).build();
37+
log.info("zookeeper 初始化完成...");
38+
return client;
39+
}
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.springboot.config;
2+
3+
import lombok.Data;
4+
import org.springframework.boot.context.properties.ConfigurationProperties;
5+
import org.springframework.stereotype.Component;
6+
7+
/**
8+
* @author dengzhiming
9+
* @date 2020/5/5 14:10
10+
*/
11+
@Data
12+
@Component
13+
@ConfigurationProperties(prefix = "zookeeper")
14+
public class ZookeeperProps {
15+
private boolean enabled ;
16+
private String server ;
17+
private String namespace ;
18+
private String digest ;
19+
private Integer sessionTimeoutMs ;
20+
private Integer connectionTimeoutMs ;
21+
private Integer maxRetries ;
22+
private Integer baseSleepTimeMs ;
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.springboot.controller;
2+
3+
import com.springboot.service.ZookeeperService;
4+
import org.springframework.web.bind.annotation.*;
5+
6+
import javax.annotation.Resource;
7+
import java.util.List;
8+
9+
/**
10+
* @author dengzhiming
11+
* @date 2020/5/5 14:15
12+
*/
13+
@RestController
14+
public class ZookeeperController {
15+
@Resource
16+
private ZookeeperService zookeeperService;
17+
18+
//查询节点数据
19+
@GetMapping("/getNodeData/{path}")
20+
public String getNodeData(@PathVariable("path") String path) throws Exception {
21+
return zookeeperService.getNodeData("/" + path);
22+
}
23+
24+
//判断节点是否存在
25+
@GetMapping("/isExistNode/{path}")
26+
public boolean isExistNode(final @PathVariable("path") String path) throws Exception {
27+
return zookeeperService.isExistNode("/" + path);
28+
}
29+
30+
//创建节点
31+
@PutMapping("/createNode/{path}/{flag}")
32+
public String createNode(@PathVariable("flag") int flag, @PathVariable("path") String path) throws Exception {
33+
// flag: 0(PERSISTENT),1(EPHEMERAL),2(PERSISTENT_SEQUENTIAL),3(EPHEMERAL_SEQUENTIAL)
34+
zookeeperService.createNode(flag, "/" + path);
35+
return "success";
36+
}
37+
38+
//设置节点数据
39+
@PutMapping("/setNodeData/{path}/{nodeData}")
40+
public String setNodeData(@PathVariable("path") String path, @PathVariable("nodeData") String nodeData) throws Exception {
41+
zookeeperService.setNodeData("/" + path, nodeData);
42+
return "success";
43+
}
44+
45+
//创建并设置节点数据
46+
@PutMapping("/createNodeAndData/{path}/{nodeData}/{flag}")
47+
public String createNodeAndData(@PathVariable("flag") int flag, @PathVariable("path") String path, @PathVariable("nodeData") String nodeData) throws Exception {
48+
zookeeperService.createNodeAndData(flag, "/" + path, nodeData);
49+
return "success";
50+
}
51+
52+
//递归获取节点数据
53+
@DeleteMapping("/getNodeChild/{path}")
54+
public List<String> getNodeChild(@PathVariable("path") String path) throws Exception {
55+
return zookeeperService.getNodeChild("/" + path);
56+
}
57+
58+
//是否递归删除节点
59+
@GetMapping("/deleteNode/{path}")
60+
public String deleteNode(@PathVariable("path") String path, @PathVariable("path") String flag) throws Exception {
61+
if ("true".equals(flag.trim())) {
62+
zookeeperService.deleteNode("/" + path, true);
63+
} else {
64+
zookeeperService.deleteNode("/" + path, false);
65+
}
66+
return "success";
67+
}
68+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.springboot.exception;
2+
3+
import org.springframework.web.bind.annotation.ControllerAdvice;
4+
import org.springframework.web.bind.annotation.ExceptionHandler;
5+
import org.springframework.web.bind.annotation.ResponseBody;
6+
7+
/**
8+
* @author dengzhiming
9+
* @date 2020/5/5 17:54
10+
*/
11+
@ControllerAdvice
12+
public class GlobalErrorHandler {
13+
@ExceptionHandler(Exception.class)
14+
@ResponseBody
15+
public String exceptionHandler(Throwable error){
16+
return error.getMessage();
17+
}
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.springboot.service;
2+
3+
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
4+
5+
import java.util.List;
6+
7+
/**
8+
* @author dengzhiming
9+
* @date 2020/5/5 14:17
10+
*/
11+
public interface ZookeeperService {
12+
/**
13+
* 判断节点是否存在
14+
*/
15+
boolean isExistNode (final String path) throws Exception;
16+
/**
17+
* 创建节点
18+
*/
19+
void createNode (int flag,String path ) throws Exception;
20+
/**
21+
* 设置节点数据
22+
*/
23+
void setNodeData (String path, String nodeData) throws Exception;
24+
/**
25+
* 创建节点
26+
*/
27+
void createNodeAndData (int flag, String path , String nodeData) throws Exception;
28+
/**
29+
* 获取节点数据
30+
*/
31+
String getNodeData (String path) throws Exception;
32+
/**
33+
* 获取节点下数据
34+
*/
35+
List<String> getNodeChild (String path) throws Exception;
36+
/**
37+
* 是否递归删除节点
38+
*/
39+
void deleteNode (String path,Boolean recursive) throws Exception;
40+
/**
41+
* 获取读写锁
42+
*/
43+
InterProcessReadWriteLock getReadWriteLock (String path) throws Exception;
44+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.springboot.service.impl;
2+
3+
import com.springboot.service.ZookeeperService;
4+
import lombok.extern.slf4j.Slf4j;
5+
import org.apache.curator.framework.CuratorFramework;
6+
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
7+
import org.apache.zookeeper.CreateMode;
8+
import org.apache.zookeeper.data.Stat;
9+
import org.springframework.stereotype.Service;
10+
11+
import javax.annotation.Resource;
12+
import java.nio.charset.StandardCharsets;
13+
import java.util.List;
14+
15+
/**
16+
* @author dengzhiming
17+
* @date 2020/5/5 14:18
18+
*/
19+
@Slf4j
20+
@Service
21+
public class ZookeeperServiceImpl implements ZookeeperService {
22+
23+
@Resource
24+
CuratorFramework client;
25+
26+
@Override
27+
public String getNodeData(String path) throws Exception {
28+
// 数据读取和转换
29+
byte[] dataByte = client.getData().forPath(path);
30+
return new String(dataByte, StandardCharsets.UTF_8);
31+
}
32+
33+
@Override
34+
public boolean isExistNode(String path) throws Exception {
35+
client.sync();
36+
Stat stat = client.checkExists().forPath(path);
37+
return stat != null;
38+
}
39+
40+
@Override
41+
public void createNode(int flag, String path) throws Exception {
42+
// 递归创建所需父节点
43+
client.create().creatingParentsIfNeeded().withMode(CreateMode.fromFlag(flag)).forPath(path);
44+
}
45+
46+
@Override
47+
public void setNodeData(String path, String nodeData) throws Exception {
48+
// 设置节点数据
49+
client.setData().forPath(path, nodeData.getBytes(StandardCharsets.UTF_8));
50+
}
51+
52+
@Override
53+
public void createNodeAndData(int flag, String path, String nodeData) throws Exception {
54+
// 创建节点,关联数据
55+
client.create().creatingParentsIfNeeded().withMode(CreateMode.fromFlag(flag))
56+
.forPath(path, nodeData.getBytes(StandardCharsets.UTF_8));
57+
}
58+
59+
@Override
60+
public List<String> getNodeChild(String path) throws Exception {
61+
return client.getChildren().forPath(path);
62+
}
63+
64+
@Override
65+
public void deleteNode(String path, Boolean recursive) throws Exception {
66+
if (recursive) {
67+
// 递归删除节点
68+
client.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
69+
} else {
70+
// 删除单个节点
71+
client.delete().guaranteed().forPath(path);
72+
}
73+
}
74+
75+
@Override
76+
public InterProcessReadWriteLock getReadWriteLock(String path) throws Exception {
77+
// 写锁互斥、读写互斥
78+
return new InterProcessReadWriteLock(client, path);
79+
}
80+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
server:
2+
port: 8080
3+
spring:
4+
application:
5+
name: springboot-zookeeper
6+
zookeeper:
7+
#开启标志
8+
enabled: true
9+
#服务器地址
10+
server: 127.0.0.1:2181
11+
#命名空间,被称为ZNode
12+
namespace: cicada
13+
#权限控制,加密
14+
digest: smile:123456
15+
#会话超时时间
16+
sessionTimeoutMs: 3000
17+
#连接超时时间
18+
connectionTimeoutMs: 60000
19+
#最大重试次数
20+
maxRetries: 2
21+
#初始休眠时间
22+
baseSleepTimeMs: 1000

0 commit comments

Comments
 (0)