SpringBoot快速整合dubbo

Spring Boot与Dubbo进行整合

添加引用

1
2
3
4
5
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.1.RELEASE</version>
</dependency>

服务提供端-provider

服务端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@SpringBootApplication
public class DubboProviderApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(DubboProviderApplication.class)
.web(WebApplicationType.SERVLET)
.listeners((ApplicationListener<ApplicationEnvironmentPreparedEvent>) event -> {
Environment environment = event.getEnvironment();
int port = environment.getProperty("embedded.zookeeper.port", int.class);
new EmbeddedZooKeeper(port, false).start();
})
.run(args);
}

}
  1. ApplicationEnvironmentPreparedEvent监听环境变量预处理事件
  2. 通过事件方式连接Zk
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Demo Service实现层。
*
* @author battleheart
*/
@Service(version = "${demo.service.version}", loadbalance = "roundrobin")
public class DemoServiceImpl implements DemoService {

@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
  1. 服务提供端通过dubbo的@Service注解进行服务的提供

服务端配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# SpringBoot应用名称
spring.application.name=dubbo-registry-zookeeper-provider-sample
# 扫描的Service包地址
dubbo.scan.base-packages=com.battleheart.dubboprovider
# Zookeeper的端口号
embedded.zookeeper.port=2181
# Dubbo Protocol
dubbo.protocol.name=dubbo
## Dubbo注册地址
dubbo.registry.address=zookeeper://127.0.0.1:${embedded.zookeeper.port}
## dubbo服务版本号
demo.service.version=1.0.0
# 服务端口
server.port=8081

服务消费端-customer

客户端代码

1
2
3
4
5
6
7
8
9
10
@Component
public class Demo {

@Reference(version = "1.0.0")
private DemoService demoService;

public String sayHello(String name) {
return demoService.sayHello(name);
}
}

配置文件

1
2
3
4
spring.application.name=annotation-consumer
embedded.zookeeper.port=2181
dubbo.registry.address=zookeeper://127.0.0.1:${embedded.zookeeper.port}
dubbo.consumer.timeout=3000

EmbeddedZooKeeper

EmbeddedZooKeeper代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
public class EmbeddedZooKeeper implements SmartLifecycle {

/**
* Logger.
*/
private static final Logger logger = LoggerFactory.getLogger(EmbeddedZooKeeper.class);

/**
* ZooKeeper client port. This will be determined dynamically upon startup.
*/
private final int clientPort;

/**
* Whether to auto-start. Default is true.
*/
private boolean autoStartup = true;

/**
* Lifecycle phase. Default is 0.
*/
private int phase = 0;

/**
* Thread for running the ZooKeeper server.
*/
private volatile Thread zkServerThread;

/**
* ZooKeeper server.
*/
private volatile ZooKeeperServerMain zkServer;

/**
* {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread.
*/
private ErrorHandler errorHandler;

private boolean daemon = true;

/**
* Construct an EmbeddedZooKeeper with a random port.
*/
public EmbeddedZooKeeper() {
clientPort = SocketUtils.findAvailableTcpPort();
}

/**
* Construct an EmbeddedZooKeeper with the provided port.
*
* @param clientPort port for ZooKeeper server to bind to
*/
public EmbeddedZooKeeper(int clientPort, boolean daemon) {
this.clientPort = clientPort;
this.daemon = daemon;
}

/**
* Returns the port that clients should use to connect to this embedded server.
*
* @return dynamically determined client port
*/
public int getClientPort() {
return this.clientPort;
}

/**
* Specify whether to start automatically. Default is true.
*
* @param autoStartup whether to start automatically
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}

/**
* {@inheritDoc}
*/
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}

/**
* Specify the lifecycle phase for the embedded server.
*
* @param phase the lifecycle phase
*/
public void setPhase(int phase) {
this.phase = phase;
}

/**
* {@inheritDoc}
*/
@Override
public int getPhase() {
return this.phase;
}

/**
* {@inheritDoc}
*/
@Override
public boolean isRunning() {
return (zkServerThread != null);
}

/**
* Start the ZooKeeper server in a background thread.
* <p>
* Register an error handler via {@link #setErrorHandler} in order to handle
* any exceptions thrown during startup or execution.
*/
@Override
public synchronized void start() {
if (zkServerThread == null) {
zkServerThread = new Thread(new ServerRunnable(), "ZooKeeper Server Starter");
zkServerThread.setDaemon(daemon);
zkServerThread.start();
}
}

/**
* Shutdown the ZooKeeper server.
*/
@Override
public synchronized void stop() {
if (zkServerThread != null) {
// The shutdown method is protected...thus this hack to invoke it.
// This will log an exception on shutdown; see
// https://issues.apache.org/jira/browse/ZOOKEEPER-1873 for details.
try {
Method shutdown = ZooKeeperServerMain.class.getDeclaredMethod("shutdown");
shutdown.setAccessible(true);
shutdown.invoke(zkServer);
} catch (Exception e) {
throw new RuntimeException(e);
}

// It is expected that the thread will exit after
// the server is shutdown; this will block until
// the shutdown is complete.
try {
zkServerThread.join(5000);
zkServerThread = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.warn("Interrupted while waiting for embedded ZooKeeper to exit");
// abandoning zk thread
zkServerThread = null;
}
}
}

/**
* Stop the server if running and invoke the callback when complete.
*/
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}

/**
* Provide an {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread. If none
* is provided, only error-level logging will occur.
*
* @param errorHandler the {@link ErrorHandler} to be invoked
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}

/**
* Runnable implementation that starts the ZooKeeper server.
*/
private class ServerRunnable implements Runnable {

@Override
public void run() {
try {
Properties properties = new Properties();
File file = new File(System.getProperty("java.io.tmpdir")
+ File.separator + UUID.randomUUID());
file.deleteOnExit();
properties.setProperty("dataDir", file.getAbsolutePath());
properties.setProperty("clientPort", String.valueOf(clientPort));

QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
quorumPeerConfig.parseProperties(properties);

zkServer = new ZooKeeperServerMain();
ServerConfig configuration = new ServerConfig();
configuration.readFrom(quorumPeerConfig);

zkServer.runFromConfig(configuration);
} catch (Exception e) {
if (errorHandler != null) {
errorHandler.handleError(e);
} else {
logger.error("Exception running embedded ZooKeeper", e);
}
}
}
}

}
文章目录
  1. 1. Spring Boot与Dubbo进行整合
    1. 1.1. 添加引用
    2. 1.2. 服务提供端-provider
      1. 1.2.1. 服务端代码
      2. 1.2.2. 服务端配置文件
    3. 1.3. 服务消费端-customer
      1. 1.3.1. 客户端代码
      2. 1.3.2. 配置文件
  2. 2. EmbeddedZooKeeper
|
载入天数...载入时分秒...