dubbo的使用
dubbo现在用的也不多,基本都在用spring cloud那一套,所以不详细写这个dubbo了。
2.demo示例
我们需要把提供者注册到dubbo注册中心,消费者去订阅
2.1:新建一个空的项目,先不建module
2.2:新建提供者(provider)模块
file->new->module,选择spring initializr
勾选上web
新建service及其实现类
public interface ProviderService { String provideSomething(); }
package com.sunsas.provider.service.impl; import com.sunsas.provider.service.ProviderService; import com.alibaba.dubbo.config.annotation.Service; import org.springframework.stereotype.Component; @Component //将服务发布出去,注意此Service是dubbo包的 @Service public class ProviderServiceImpl implements ProviderService { @Override public String provideSomething() { return "something"; } }
引入dubbo依赖
<!-- 引入spring-boot-starter以及dubbo和curator的依赖 --> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>0.2.0</version> </dependency>
修改application.properties
server.port=8082 # 服务名称,保持唯一 dubbo.application.name=provider # zookeeper地址,用于从中获取注册的服务 dubbo.registry.address=zookeeper://127.0.0.1:2181 dubbo.scan.base-packages=com.sunsas.provider.service
appliacation 类加上@EnableDubbo注解
@EnableDubbo @SpringBootApplication public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
启动provider项目,注意需要先启动zookeeper。
2.3:新建消费者(consumer)模块
file->new->module,选择spring initializr,同样选中web模块,引入dubbo依赖
<!-- 引入spring-boot-starter以及dubbo和curator的依赖 --> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>0.2.0</version> </dependency>
修改application.properties
server.port=8081 # 服务名称,保持唯一 dubbo.application.name=consumer # zookeeper地址,用于从中获取注册的服务 dubbo.registry.address=zookeeper://127.0.0.1:2181
新建service类,这里直接用类,没有实现接口。
import com.alibaba.dubbo.config.annotation.Reference; import com.sunsas.provider.service.ProviderService; import org.springframework.stereotype.Service; @Service public class ConsumerService { @Reference private ProviderService providerService; public String consumer(){ return providerService.provideSomething(); } }
还要复制provider中的ProviderService
package com.sunsas.provider.service;
public interface ProviderService {
String provideSomething();
}
新建controller测试接口
import com.sunsas.comsumer.service.ConsumerService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class TestController { @Resource private ConsumerService consumerService; @RequestMapping("/test") public String test(){ return consumerService.consumer(); } }
结构如图:
发送请求测试
http://localhost:8081/test
需要注意的是复制ProviderService路劲要一致,否则可能空指针。