dubbo 使用示例
相关依赖
org.apache.dubbo dubbo-spring-boot-starter3.0.5 org.apache.curator curator-recipes5.2.0 org.apache.curator curator-x-discovery5.2.0
provider
application.yml
dubbo: application: name: dubbo-provider register-mode: instance registry: address: zookeeper://localhost:2181 group: dubbo4 #register-mode: instance protocol: name: dubbo port: 20880
HelloService
public interface HelloService { String hello(); }
HelloService2
public interface HelloService2 { String hello2(); }
HelloServiceImpl
@DubboService //使用注解@DubboService暴露服务 public class HelloServiceImpl implements HelloService { @Override public String hello() { System.out.println("hello provider"); return "hello provider"; } }
HelloService2Impl
@DubboService //使用注解@DubboService暴露服务 public class HelloService2Impl implements HelloService2 { @Override public String hello2() { System.out.println("hello provider2"); return "hello provider2"; } }
DemoApplication:项目启动类添加注解@EnableDubbo
@EnableDubbo //扫描本包及子包,处理@DubboService注解(服务暴露) @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
conusmer
application.yml
dubbo: application: name: dubbo-consumer register-mode: instance registry: address: zookeeper://localhost:2181 group: dubbo4 protocol: name: dubbo port: 20880 server: port: 8081
HelloService
public interface HelloService { String hello(); }
HelloService2
public interface HelloService2 { String hello2(); }
HelloController
@RestController public class HelloController { @DubboReference //引用远程服务 private HelloService helloService; @DubboReference //引用远程服务 private HelloService2 helloService2; @RequestMapping("/hello") public String hello(){ System.out.println(helloService.hello()); System.out.println(helloService2.hello2()); return "hello consumer 2"; } }
DemoApplication:项目启动类,添加@EnableDubbo注解
@EnableDubbo //扫描本包及子包,处理@DubboReference注解(远程服务注入) @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
使用测试
zookeeper注册中心
localhost:8080/hello,控制台输出:
2022-01-28 14:43:08.545 INFO 1515 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 2.82 seconds (JVM running for 8.366) 2022-01-28 14:48:12.824 INFO 1515 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2022-01-28 14:48:12.824 INFO 1515 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2022-01-28 14:48:12.825 INFO 1515 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms hello provider hello provider2
消费端成功调用远程服务
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)