当 Service1Bootstrap 启动后,应用 application1 将出现在 Nacos 控制台界面。
============================================================================
定义service1父工程,pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns=“http://maven.apache.org/POM/4.0.0”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
nacos‐micro‐service
com.demo.nacos
1.0-SNAPSHOT
4.0.0
service‐1
pom
service‐1‐api
service‐1‐server
为了方便其它服务调用dubbo服务,专门定义api工程,此工程将作为jar被其它工程依赖。
定义service-1-api工程,pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns=“http://maven.apache.org/POM/4.0.0”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
service‐1
com.demo.nacos
1.0-SNAPSHOT
4.0.0
service‐1‐api
定义服务接口:
package com.demo.microservice.service1.api;
/**
-
Description:
-
DATE: 2022/1/27 11:09
*/
public interface ConsumerService {
public String service();
}
(1)初始化 service-1-server Maven 工程
与服务提供方 Maven工程类似,需添加相关 Maven 依赖:
<?xml version="1.0" encoding="UTF-8"?><project xmlns=“http://maven.apache.org/POM/4.0.0”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
service‐1
com.demo.nacos
1.0-SNAPSHOT
4.0.0
service‐1‐server
com.demo.nacos
service‐1‐api
1.0-SNAPSHOT
com.demo.nacos
service‐2‐api
1.0-SNAPSHOT
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config
com.alibaba.cloud
spring-cloud-starter-dubbo
(2)实现 Dubbo 服务
package com.demo.microservice.service1.service;
import com.demo.microservice.service1.api.ConsumerService;
import com.demo.microservice.service2.api.ProviderService;
/**
-
Description:
-
DATE: 2022/1/27 11:13
*/
@org.apache.dubbo.config.annotation.Service
public class ConsumerServiceImpl implements ConsumerService {
@org.apache.dubbo.config.annotation.Reference
ProviderService providerService;
@Override
public String service() {
String service = providerService.service();
return “Consumer invoke |”+service;
}
}
注意:使用@org.apache.dubbo.config.annotation.Service标记dubbo服务
(3)配置 Dubbo 服务
Service2 作为Dubbo服务消费方配置与服务提供方类似,注意,service1不仅是消费方,同时还是服务提供方:
server:
port: ${port:56030} #启动端口 命令行注入
spring:
application:
name: service1
main:
allow‐bean‐definition‐overriding: true # Spring Boot 2.1 需要设定
cloud:
nacos:
discovery:
server‐addr: 127.0.0.1:8848
namespace: 20dd9cd5-8ce6-4f73-8380-dfa3074ce5a8
cluster‐name: DEFAULT
config:
server‐addr: 127.0.0.1:8848 # 配置中心地址
file‐extension: yaml
namespace: 20dd9cd5-8ce6-4f73-8380-dfa3074ce5a8 # 开发环境
group: NACOS_MICROSERVICE_GROUP # xx业务
dubbo:
scan:
dubbo 服务扫描基准包
base‐packages: com.demo.microservice
<