我们知道dubbo的运行原理如图所示,服务端向注册中心注册服务,客户端订阅注册中心获取服务地址,然后在调用服务
我们再此选用的注册中心为zookeeper(当然也可以选用nacos)
1.下载并启动zookeeper
2.搭建springboot项目,引入dubbo的jar包
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
3.配置服务端
//application.properties
//注册项目服务名
dubbo.application.name = dubbo-provider
//dubbo协议名称
dubbo.protocol.name = dubbo
//dubbo占用端口
dubbo.protocol.port = 20881
//zookeeper地址
dubbo.registry.address = zookeeper://localhost:2181
配置启动类
@EnableDubbo
@SpringBootApplication
public class DubboApplication {
public static void main(String[] args) {
SpringApplication.run(DubboApplication.class, args);
}
}
在要暴露的实现方法上注解@Service
package com.example.demo.Service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.example.demo.Service.DemoService;
//Service为dubbo jar中的Service注解,不是spring 的Service注解
@Service
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "hi,"+name;
}
}
服务端配置完成
客户端配置
在application.properties中增加配置
dubbo.application.name=consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
package com.example.demo.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.example.demo.Service.DemoService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@Reference
private DemoService demoService;
@RequestMapping("/SayHello")
public String sayHello(String name) {
return demoService.sayHello(name);
}
}
在需要dubbo注入的Service上增加@Reference注解
启动客户端
访问接口
dubbo调用成功,返回成功