Dubbo入门学习三—xml配置方式

在我看来Dubbo最为方便的还是通过Spring 容器来加载Dubbo的Bean配置。而最便捷的学习途径就是看官方文档和代码。这里贴出我的代码:NEZHA的GitHub代码仓库

这里主要分成三部分:

1. API
2. Provider
3. Consumer

1、API的设计

package com.nezha.demo.dubbo;

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

2、Provide的代码

1.api接口的实现类

package com.nezha.demo.dubbo;

import com.alibaba.dubbo.rpc.RpcContext;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DemoServiceImpl implements DemoService {
    @Override
    public String sayHello(String name) {
        System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
        return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress();
    }
}

2.Dubbo的配置文件

文件位于resources包下面:/resources/spring/dubbo-demo-provider.xml




    
    

    
    

    
    

    
    

    
    


3.Provider服务提供者

package com.nezha.demo.dubbo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Provider {

    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/dubbo-demo-provider.xml"});
        context.start();
        System.in.read(); // press any key to exit
    }
}

3、Consumer的代码

1.Dubbo的xml配置




    
    

    
    

    
    


2.Consumer的代码

package com.nezha.demo.dubbo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Consumer {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/dubbo-demo-consumer.xml"});
        context.start();
        // get remote service proxy
        DemoService demoService = (DemoService) context.getBean("demoService");
        while (true) {
            try {
                Thread.sleep(1000);
                // call remote method
                String hello = demoService.sayHello("world");
                // get result
                System.out.println(hello);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(Dubbo入门学习三—xml配置方式)