Dubbo Spring Cloud 服务消费方开发步骤

注册中心采用阿里巴巴Nacos

接口定义

1
2
3
4
5
6
7
8
public interface UserService {

boolean save(User user);

boolean remove(Long userId);

Collection<User> findAll();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface RestService {

String param(String param);

String params(int a, String b);

String headers(String header, String header2, Integer param);

String pathVariables(String path1, String path2, String param);

String form(String form);

User requestBodyMap(Map<String, Object> data, String param);

Map<String, Object> requestBodyUser(User user);
}

依赖引入

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
<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>

<!-- Spring Cloud Open Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- Spring Retry -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>

<!-- Sample API -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-dubbo-sample-api</artifactId>
<version>${project.version}</version>
</dependency>

<!-- Dubbo Spring Cloud Starter -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>

<!-- Spring Cloud Nacos Service Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

</dependencies>

项目配置

  • bootstrap.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
spring:
application:
name: spring-cloud-alibaba-dubbo-consumer
main:
allow-bean-definition-overriding: true
profiles: nacos
cloud:
nacos:
username: test
password: test
discovery:
enabled: true
register-enabled: true
server-addr: 192.168.1.5:8848
context-path: /nacos
ephemeral: false

ribbon:
nacos:
enabled: true
  • application.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
dubbo:
cloud:
# The subscribed services in consumer side
subscribed-services: ${provider.application.name}
protocols:
dubbo:
port: -1
consumer:
check: false

provider:
application:
name: spring-cloud-alibaba-dubbo-provider

消费实现

dubbo服务基本调用

1
2
3
4
5
@DubboReference
private UserService userService;

@DubboReference(version = "1.0.0", protocol = "dubbo")
private RestService restService;

FeignClient

  • 走http协议
1
2
3
4
@FeignClient("${provider.application.name}")
public interface FeignRestService {
...
}
  • 走dubbo协议
1
2
3
4
5
@FeignClient("${provider.application.name}")
@DubboTransported(protocol = "dubbo")
public interface DubboFeignRestService {
...
}

RestTemplate

  • 走http协议
1
2
3
4
5
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
  • 走dubbo协议
1
2
3
4
5
6
@Bean
@LoadBalanced
@DubboTransported
public RestTemplate restTemplate() {
return new RestTemplate();
}

完整代码

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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import com.alibaba.cloud.dubbo.annotation.DubboTransported;
import com.alibaba.cloud.dubbo.service.RestService;
import com.alibaba.cloud.dubbo.service.User;
import com.alibaba.cloud.dubbo.service.UserService;

import org.apache.dubbo.config.annotation.DubboReference;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

/**
* Dubbo Spring Cloud Consumer Bootstrap
*/
@EnableDiscoveryClient
@EnableAutoConfiguration
@EnableFeignClients
@EnableScheduling
@EnableCaching
public class DubboSpringCloudConsumerBootstrap {

@DubboReference
private UserService userService;

@DubboReference(version = "1.0.0", protocol = "dubbo")
private RestService restService;

@Autowired
@Lazy
private FeignRestService feignRestService;

@Autowired
@Lazy
private DubboFeignRestService dubboFeignRestService;

@Value("${provider.application.name}")
private String providerApplicationName;

@Autowired
@LoadBalanced
private RestTemplate restTemplate;

@Bean
public ApplicationRunner userServiceRunner() {
return arguments -> {

User user = new User();
user.setId(1L);
user.setName("小马哥");
user.setAge(33);

// save User
System.out.printf("UserService.save(%s) : %s\n", user,
userService.save(user));

// find all Users
System.out.printf("UserService.findAll() : %s\n", user,
userService.findAll());

// remove User
System.out.printf("UserService.remove(%d) : %s\n", user.getId(),
userService.remove(user.getId()));

};
}

@Bean
public ApplicationRunner callRunner() {
return arguments -> {
callAll();
};
}

private void callAll() {

// To call /path-variables
callPathVariables();

// To call /headers
callHeaders();

// To call /param
callParam();

// To call /params
callParams();

// To call /request/body/map
callRequestBodyMap();
}

@Scheduled(fixedDelay = 10 * 1000L)
public void onScheduled() {
callAll();
}

private void callPathVariables() {
// Dubbo Service call
System.out.println(restService.pathVariables("a", "b", "c"));
// Spring Cloud Open Feign REST Call (Dubbo Transported)
System.out.println(dubboFeignRestService.pathVariables("c", "b", "a"));
// Spring Cloud Open Feign REST Call
//System.out.println(feignRestService.pathVariables("b", "a", "c"));

// RestTemplate call
System.out.println(restTemplate.getForEntity(
"http://" + providerApplicationName + "//path-variables/{p1}/{p2}?v=c",
String.class, "a", "b"));
}

private void callHeaders() {
// Dubbo Service call
System.out.println(restService.headers("a", "b", 10));
// Spring Cloud Open Feign REST Call (Dubbo Transported)
System.out.println(dubboFeignRestService.headers("b", 10, "a"));
// Spring Cloud Open Feign REST Call
//System.out.println(feignRestService.headers("b", "a", 10));
}

private void callParam() {
// Dubbo Service call
System.out.println(restService.param("appblog.cn"));
// Spring Cloud Open Feign REST Call (Dubbo Transported)
System.out.println(dubboFeignRestService.param("appblog.cn"));
// Spring Cloud Open Feign REST Call
//System.out.println(feignRestService.param("appblog.cn"));
}

private void callParams() {
// Dubbo Service call
System.out.println(restService.params(1, "1"));
// Spring Cloud Open Feign REST Call (Dubbo Transported)
System.out.println(dubboFeignRestService.params("1", 1));
// Spring Cloud Open Feign REST Call
//System.out.println(feignRestService.params(1, "1"));

// RestTemplate call
System.out.println(restTemplate.getForEntity(
"http://" + providerApplicationName + "/param?param=小马哥", String.class));
}

private void callRequestBodyMap() {

Map<String, Object> data = new HashMap<>();
data.put("id", 1);
data.put("name", "小马哥");
data.put("age", 33);

// Dubbo Service call
System.out.println(restService.requestBodyMap(data, "Hello,World"));
// Spring Cloud Open Feign REST Call (Dubbo Transported)
System.out.println(dubboFeignRestService.requestBody("Hello,World", data));
// Spring Cloud Open Feign REST Call
//System.out.println(feignRestService.requestBody("Hello,World", data));

// RestTemplate call
System.out.println(restTemplate.postForObject(
"http://" + providerApplicationName + "/request/body/map?param=小马哥", data,
User.class));
}

@Bean
@LoadBalanced
@DubboTransported
public RestTemplate restTemplate() {
return new RestTemplate();
}

public static void main(String[] args) {
new SpringApplicationBuilder(DubboSpringCloudConsumerBootstrap.class)
.properties("spring.profiles.active=nacos").run(args);
}

@FeignClient("${provider.application.name}")
public interface FeignRestService {

@GetMapping("/param")
String param(@RequestParam("param") String param);

@PostMapping("/params")
String params(@RequestParam("a") int a, @RequestParam("b") String b);

@PostMapping(value = "/request/body/map", produces = APPLICATION_JSON_VALUE)
User requestBody(@RequestParam("param") String param,
@RequestBody Map<String, Object> data);

@GetMapping("/headers")
String headers(@RequestHeader("h2") String header2,
@RequestHeader("h") String header, @RequestParam("v") Integer value);

@GetMapping("/path-variables/{p1}/{p2}")
String pathVariables(@PathVariable("p2") String path2,
@PathVariable("p1") String path1, @RequestParam("v") String param);

}

@FeignClient("${provider.application.name}")
@DubboTransported(protocol = "dubbo")
public interface DubboFeignRestService {

@GetMapping("/param")
String param(@RequestParam("param") String param);

@PostMapping("/params")
String params(@RequestParam("b") String paramB, @RequestParam("a") int paramA);

@PostMapping(value = "/request/body/map", produces = APPLICATION_JSON_UTF8_VALUE)
User requestBody(@RequestParam("param") String param,
@RequestBody Map<String, Object> data);

@GetMapping("/headers")
String headers(@RequestHeader("h2") String header2,
@RequestParam("v") Integer value, @RequestHeader("h") String header);

@GetMapping("/path-variables/{p1}/{p2}")
String pathVariables(@RequestParam("v") String param,
@PathVariable("p2") String path2, @PathVariable("p1") String path1);

}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :