第一次使用 dubbo+springboot+zookeeper 的测试过程
1.项目结构 (我用的是gradle)
总共分三个模块
dubbo-demo-api:提供者消费者公用的接口
public interface DemoService {
String sayHello(String name);
}
dubbo-demo-provider:服务提供者,向zk注册服务信息
实现接口代码:
import com.demo.dubbo.api.DemoService;
import org.apache.dubbo.config.annotation.Service;
@Service(version = "${mistra.service.version}")
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
启动类代码:
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDubbo
public class ProviderStart {
public static void main(String[] args) throws Exception {
SpringApplication.run(ProviderStart.class, args);
}
}
dubbo-demo-consumer:服务消费者,订阅zk中注册的服务
实现接口方法代码:
import org.apache.dubbo.config.annotation.Reference;
import com.demo.dubbo.api.DemoService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoServiceImpl {
@Reference(version = "${mistra.service.version}")
private DemoService demoService;
@RequestMapping("/sayHello/{name}")
public String sayHello(@PathVariable("name") String name) {
return demoService.sayHello(name);
}
}
启动类代码:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumerStart {
public static void main(String[] args) throws Exception {
SpringApplication.run(ConsumerStart.class, args);
}
}
依赖:(我用的是gradle)
// log
compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
// dubbo
compile group: 'org.apache.dubbo', name: 'dubbo', version: '2.7.0'
compile group: 'org.apache.dubbo', name: 'dubbo-spring-boot-starter', version: '2.7.0'
compile group: 'org.apache.curator', name: 'curator-framework', version: '4.2.0'
compile group: 'org.apache.curator', name: 'curator-recipes', version: '4.2.0'
// springboot
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '2.1.3.RELEASE'
每个模块具体的代码网上有很多,我也是网上copy的,还有注解的含义我就不一一解释了,网上解释很详细可以自己去看看
然后就可以启动了,先启动ProviderStart,再启动ConsumerStart
注意:zookeeper 默认版本是3.5.4-beta,版本不一样可能会报错