Dubbo入门学习四:SpringBoot下使用XML配置方式

话不多说!先上我的代码:Demo
设计的子项目有:provider , consumertest-dubbo-boot-api


  • 我的技术博客:https://nezha.github.io,https://nezhaxiaozi.coding.me
  • 我的地址:https://www.jianshu.com/u/a5153fbb0434

其中:

test-dubbo-boot-api:是暴露的接口。
provider:服务的提供者,它实现了接口。
consumer:服务的消费者。

代码实现

1.暴露的接口:test-dubbo-boot-api

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

2.服务提供者:provider

DubboDemoServiceImpl

@Service
public class DubboDemoServiceImpl 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();
    }
}

resources/dubbo/dubbo-provider.xml



    
    
    
    
    
    
    
    
    
    

ProviderApplication

@SpringBootApplication
@ImportResource("classpath:dubbo/*.xml")
public class ProviderApplication {
    public static void main(String[] args) throws Exception{
        SpringApplication.run(ProviderApplication.class, args);
        System.in.read();
    }
}

3.服务消费者:consumer

resources/dubbo/dubbo-consumer.xml



    
    
    
    
    
    

resources/dubbo.properties

dubbo.provider.version=1.0.0
zookeeper.connect=127.0.0.1:2181

PropertiesConfig

//2.第二种方式
@Configuration
@PropertySource("classpath:dubbo.properties")
@ImportResource({"classpath:dubbo/*.xml"})
public class PropertiesConfig {
}

ConsumerApplication

@SpringBootApplication
//1.第一种方式,如果直接使用xml方式的话,注释掉配置类:PropertiesConfig
//@ImportResource("classpath:dubbo/consumer.xml")
public class ConsumerApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(ConsumerApplication.class, args);
        DemoService demoService = (DemoService) ctx.getBean("demoService");
        while (true) {
            try {
                Thread.sleep(1000);
                // call remote method
                String hello = demoService.sayHello("world, NEZHA");
                // get result
                System.out.println(hello);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }
}

参考文献

  1. spring boot配置dubbo(XML)
  2. Spring Boot 中使用 Dubbo 详解

你可能感兴趣的:(Dubbo入门学习四:SpringBoot下使用XML配置方式)