在 Java 里,Dubbo 与 Spring 的集成是非常常见且官方支持良好的。根据使用方式不同,主要有以下几种集成方式:
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
接口
public interface HelloService {
String sayHello(String name);
}
实现类
public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
return "Hello " + name;
}
}
Spring 配置(provider.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo">
<dubbo:application name="dubbo-provider"/>
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<dubbo:protocol name="dubbo" port="20880"/>
<dubbo:service interface="com.example.HelloService"
ref="helloService"/>
<bean id="helloService" class="com.example.HelloServiceImpl"/>
</beans>
启动
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("provider.xml");
context.start();
Spring 配置(consumer.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo">
<dubbo:application name="dubbo-consumer"/>
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<dubbo:reference id="helloService"
interface="com.example.HelloService"/>
</beans>
使用
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("consumer.xml");
HelloService service = (HelloService) context.getBean("helloService");
System.out.println(service.sayHello("Dubbo"));
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
dubbo:
application:
name: dubbo-provider
registry:
address: zookeeper://127.0.0.1:2181
protocol:
name: dubbo
port: 20880
@DubboService
public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
return "Hello " + name;
}
}
@SpringBootApplication
@EnableDubbo
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class);
}
}
@RestController
public class TestController {
@DubboReference
private HelloService helloService;
@GetMapping("/hello")
public String hello() {
return helloService.sayHello("Spring Boot");
}
}
@SpringBootApplication
@EnableDubbo
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class);
}
}
✅ Dubbo 本质是 Spring 的扩展
✅ @DubboService ≈ <dubbo:service>
✅ @DubboReference ≈ <dubbo:reference>
✅ @EnableDubbo 开启 Dubbo 自动扫描
如果你需要:
可以继续问我。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。