我分为了三个模块,一个 api, 一个 provider, 一个 consumer. 其中 api 是公用的模块,服务端为它提供实现,客户端只依赖 api 编程。Provider 与 Consumer 一定要在不同的 Moddule 中,否则就不过经过 Dubbo 这个 RPC 框架而是调用的本地接口实现了。
服务接口
比如我们的 api 中有一个 String sayHello(String name) 的接口:
1
2
3
4
5
6
7
8
9
package com.youthlin.demo.dubbo.api.service;
/**
* Created by lin on 2016-11-19-019.
* Hello Service
*/public interface HelloService {
String sayHello(String name);
}
服务端
接口实现
然后在服务端是具体的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.youthlin.demo.dubbo.provider.service;
import com.youthlin.demo.dubbo.api.service.HelloService;
/**
* Created by lin on 2016-11-19-019.
* Impl
*/public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
return"Hello, "+ name;
}
}
package com.youthlin.demo.dubbo.consumer.main;
import com.youthlin.demo.dubbo.api.service.HelloService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/*** Created by lin on 2016-11-19-019.* consumer
*/public class Consumer {
private static final Logger log = LoggerFactory.getLogger(Consumer.class);
public static void main(String[] args) {
log.debug("Consumer is starting...");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"consumer.xml"});
log.debug("context is loaded.");
context.start();
log.debug("context started.");
// Caused by: java.lang.IllegalStateException:
// Failed to check the status of the service com.youthlin.demo.dubbo.api.service.HelloService.// No provider available for the service com.youthlin.demo.dubbo.api.service.HelloService
// from the url multicast://224.5.6.7:1234/com.alibaba.dubbo.registry.RegistryService
//?anyhost=true&application=consumer-of-helloworld-app&check=false&dubbo=2.5.3//&interface=com.youthlin.demo.dubbo.api.service.HelloService&methods=sayHello
//&pid=1536&side=consumer×tamp=1479564027023// to the consumer 192.168.191.1 use dubbo version 2.5.3// telnet 一次就好了?……// telnet 192.168.31.19720800//其中地址是 provider log 中显示的地址 HelloService helloService = (HelloService) context.getBean("helloService"); //获取远程服务代理 log.debug("Service loaded.");
String hello = helloService.sayHello("world"); //执行远程方法 log.debug("invoke result = {}", hello);
System.out.println(hello); //显示调用结果 }
}
or
or
Map parameters = application.getParameters();
if (parameters == null) {
parameters = new HashMap<>(4);
application.setParameters(parameters);
}
parameters.put("unicast", "false");
Reader Echoes
4 comments