Dubbo Spring Cloud 服务提供方(非Web应用)开发步骤

注册中心采用阿里巴巴Nacos
服务容器为Netty,端口为9090
dubbo协议在20880+n端口暴露服务

接口

接口定义

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
import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Logger Utilities.
*/
public abstract class LoggerUtils {

private static final Logger logger = LoggerFactory.getLogger(LoggerUtils.class);

public static void log(String url, Object result) {
String message = String
.format("The client[%s] uses '%s' protocol to call %s : %s",
RpcContext.getContext().getRemoteHostName(),
RpcContext.getContext().getUrl() == null ? "N/A"
: RpcContext.getContext().getUrl().getProtocol(),
url, result);
if (logger.isInfoEnabled()) {
logger.info(message);
}
}

}

依赖引入

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

<!-- Resolve the Dubbo REST RPC issue -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<!-- Resolve the Spring Cloud registration issue -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</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>

<!-- REST support dependencies -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>

<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
</dependency>

<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
</dependency>

<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-netty4</artifactId>
</dependency>

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>

<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
</dependency>

<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
</dependency>

<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

</dependencies>

项目配置

  • bootstrap.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
spring:
application:
name: spring-cloud-alibaba-dubbo-provider
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
  • application.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
dubbo:
scan:
base-packages: com.alibaba.cloud.dubbo.service
protocols:
dubbo:
name: dubbo
port: -1
rest:
name: rest
port: 9090
server: netty
feign:
hystrix:
enabled: true

服务实现

1
2
3
4
5
6
7
8
9
10
11
@EnableDiscoveryClient
@EnableAutoConfiguration
public class DubboSpringCloudProviderBootstrap {

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

}
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
import org.apache.dubbo.config.annotation.DubboService;

/**
* In-Memory {@link UserService} implementation.
*/
@DubboService(protocol = "dubbo")
public class InMemoryUserService implements UserService {

private Map<Long, User> usersRepository = new HashMap<>();

@Override
public boolean save(User user) {
return usersRepository.put(user.getId(), user) == null;
}

@Override
public boolean remove(Long userId) {
return usersRepository.remove(userId) != null;
}

@Override
public Collection<User> findAll() {
return usersRepository.values();
}
}
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
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.alibaba.cloud.dubbo.util.LoggerUtils.log;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

/**
* Default {@link RestService}.
*/
@DubboService(version = "1.0.0", protocol = { "dubbo", "rest" })
@Path("/")
public class StandardRestService implements RestService {

private Logger logger = LoggerFactory.getLogger(getClass());

@Override
@Path("param")
@GET
public String param(@QueryParam("param") String param) {
log("/param", param);
return param;
}

@Override
@Path("params")
@POST
public String params(@QueryParam("a") int a, @QueryParam("b") String b) {
log("/params", a + b);
return a + b;
}

@Override
@Path("headers")
@GET
public String headers(@HeaderParam("h") String header,
@HeaderParam("h2") String header2, @QueryParam("v") Integer param) {
String result = header + " , " + header2 + " , " + param;
log("/headers", result);
return result;
}

@Override
@Path("path-variables/{p1}/{p2}")
@GET
public String pathVariables(@PathParam("p1") String path1,
@PathParam("p2") String path2, @QueryParam("v") String param) {
String result = path1 + " , " + path2 + " , " + param;
log("/path-variables", result);
return result;
}

// @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913
// @CookieValue also does not support

@Override
@Path("form")
@POST
public String form(@FormParam("f") String form) {
return String.valueOf(form);
}

@Override
@Path("request/body/map")
@POST
@Produces(APPLICATION_JSON_VALUE)
public User requestBodyMap(Map<String, Object> data,
@QueryParam("param") String param) {
User user = new User();
user.setId(((Integer) data.get("id")).longValue());
user.setName((String) data.get("name"));
user.setAge((Integer) data.get("age"));
log("/request/body/map", param);
return user;
}

@Path("request/body/user")
@POST
@Override
@Consumes(MediaType.APPLICATION_JSON)
public Map<String, Object> requestBodyUser(User user) {
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

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

访客数 : | 访问量 :