下载 nacos 后并启动:
nacos 下载(官网:)
启动 nacos (在下载好的 nacos 的bin 目录下 cmd 启动 nacos):startup.cmd -m standalone
![](https://img-blog.csdnimg.cn/img_convert/bab7b4eee7f2092247786b1c2ae2b7ae.png)
添加配置:
在项目中的 pom.xml 文件中加入 dubbo、nacos 的依赖(注意版本,且服务提供者和消费者都加入依赖):
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>3.0.9</version>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.1.0</version>
</dependency>
在项目中的 application.yml 中添加配置信息(服务提供者和消费者都加入):
// 服务提供者/调用者
dubbo:
application:
name: dubbo-springboot-demo-provider // 服务提供者的名称
protocol: // 协议
name: dubbo
port: -1 // 端口(使用 -1 即可)
registry:
id: nacos-registry
address: nacos://localhost:8848 // nacos 注册中心的本地地址端口
写上注解:
在项目的主类中(@EnableDubbo)(服务提供者和消费者都加入):
@EnableDubbo
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
在想要提供服务的类中的注解(@DubboService)(只在发布者的要提供服务的类中写):
@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
System.out.println("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
return "Hello " + name;
}
}
启动之后进入 nacos 访问路径即可查看服务是否挂上 nacos 注册中心上(账号密码都是:nacos):
http://192.168.116.1:8848/nacos/index.html
在消费者的主类中:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
@EnableDubbo
@Service
public class YuapiGatewayApplication {
@DubboReference // dubbo 的注解,就可以引用在 nacos 中注册好的 demoService(自己写的方法/接口)
private DemoService demoService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YuapiGatewayApplication.class, args);
YuapiGatewayApplication application = context.getBean(YuapiGatewayApplication.class);
String result = application.doSayHello("world");
String result2 = application.doSayHello2("world");
System.out.println("result: " + result);
System.out.println("result: " + result2);
}
public String doSayHello(String name) {
return demoService.sayHello(name);
}
public String doSayHello2(String name) {
return demoService.sayHello2(name);
}
}
弄完之后启动项目即可(先启动发布者的项目,在启动调用者的项目)