dubbo

DubboDemo

springboot + dubbo 3.0

1.定义服务接口

    public interface DemoService {
        String sayHello(String name);
    }

2.提供方

2.1 实现接口并暴露服务

    @DubboService
    public class DemoServiceImpl implements DemoService {
        @Override
        public String sayHello(String name) {
            System.out.println("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
            return "Hello " + name;
        }
    }

2.2 提供者主SpringBoot 主函数

    @SpringBootApplication
    @EnableDubbo
    public class ProviderApplication {
        public static void main(String[] args) throws Exception {
            new EmbeddedZooKeeper(2181, false).start();

            SpringApplication.run(ProviderApplication.class, args);
            System.out.println("dubbo service started");
            new CountDownLatch(1).await();
        }
    }

2.3 配置 application.yml 文件

    dubbo:
    application:
        name: dubbo-springboot-demo-provider
    protocol:
        name: dubbo
        port: -1
    registry:
        id: zk-registry
        address: zookeeper://127.0.0.1:2181
    config-center:
        address: zookeeper://127.0.0.1:2181
    metadata-report:
        address: zookeeper://127.0.0.1:2181

3.消费者

3.1 远程服务调用

    @SpringBootApplication
    @Service
    @EnableDubbo
    public class ConsumerApplication {
        @DubboReference
        private DemoService demoService;
        
        public String doSayHello(String name) {
            return demoService.sayHello(name);
        }

        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args);
            ConsumerApplication application = context.getBean(ConsumerApplication.class);
            String result = application.doSayHello("world");
            System.out.println("result: " + result);
        }
    }

3.2 配置 application.yml

    dubbo:
    application:
        name: dubbo-springboot-demo-consumer
    protocol:
        name: dubbo
        port: -1
    registry:
        id: zk-registry
        address: zookeeper://127.0.0.1:2181
    config-center:
        address: zookeeper://127.0.0.1:2181
    metadata-report:
        address: zookeeper://127.0.0.1:2181
posted @ 2022-10-28 11:09  古拉加斯·浩二  阅读(42)  评论(0)    收藏  举报