Dubbo使用详解(手把手教你4步使用)

Dubbo使用详解(手把手教你4步使用)-mikechen

Dubbo使用经常用到,以下是一个Dubbo使用示例,涉及到服务的提供者和消费者,主要分为如下4个步骤。

1.定义一个服务接口

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

 

2.服务提供者需要实现该接口

public class HelloServiceImpl implements HelloService {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name;
    }
}

 

3.配置Dubbo的服务提供者和消费者

1)配置服务提供者

在服务提供者端,需要在dubbo-provider.xml中进行配置:

<dubbo:application name="provider-app" />
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<dubbo:protocol name="dubbo" port="20880" />
<dubbo:service interface="com.example.HelloService" ref="helloService" />

<bean id="helloService" class="com.example.HelloServiceImpl" />

 

2)配置服务消费者

在服务消费者端,需要在dubbo-consumer.xml中进行配置:

<dubbo:application name="consumer-app" />
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<dubbo:reference id="helloService" interface="com.example.HelloService" />

<bean id="helloService" class="com.example.HelloServiceImpl" />

接下来,启动Zookeeper注册中心,并分别启动服务提供者和消费者应用。

 

4.Dubbo获取远程服务

在消费者端,可以通过Dubbo的引用来获取远程服务:

public class ConsumerApp {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dubbo-consumer.xml");
        context.start();
        
        HelloService helloService = (HelloService) context.getBean("helloService");
        String result = helloService.sayHello("Alice");
        System.out.println(result);
        
        context.close();
    }
}

这样,消费者就可以调用服务提供者的方法,并获得返回结果。

mikechen

mikechen睿哥,10年+大厂架构经验,资深技术专家,就职于阿里巴巴、淘宝、百度等一线互联网大厂。

关注「mikechen」公众号,获知最新一线技术干货!

评论交流
    说说你的看法