【Spring Boot 3】整合nacos + Dubbo3 的Spring cloud Alibaba项目
整合nacos + Dubbo3的Spring cloud Alibaba项目,你需要做以下几步:
- 在
pom.xml
中添加Spring Cloud Alibaba Nacos和Dubbo3的依赖。
<dependencies>
<!-- Spring Cloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Dubbo3 Spring Cloud Starter -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-cloud-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
- 在
application.properties
或application.yml
中配置Nacos服务器地址和Dubbo3相关配置。
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 # Nacos服务器地址
dubbo:
scan:
base-packages: com.example.service # Dubbo服务所在的包
protocol:
name: dubbo # 使用dubbo协议
port: -1 # 端口设置为-1表示自动分配端口
registry:
address: spring-cloud://localhost # 指定注册中心地址
- 在Spring Boot启动类上添加
@EnableDubbo
注解启用Dubbo3。
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableDubbo
@SpringBootApplication
public class Dubbo3Application {
public static void main(String[] args) {
SpringApplication.run(Dubbo3Application.class, args);
}
}
- 创建服务提供者和服务消费者。
提供者示例:
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;
@DubboService(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
String clientIp = RpcContext.getContext().getRemoteAddressString();
return "Hello, " + name + ", request from client: " + clientIp;
}
}
消费者示例:
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public c
评论已关闭