dubbo+spring实例搭建

来源:互联网 发布:卓大王yeile知乎 编辑:程序博客网 时间:2024/05/21 07:15
1.定义服务接口

该接口需单独打包,在服务提供方和消费方共享

package com.hthl.api.service.inf;public interface DemoService {public String sayHello(String name);}
2.服务提供方
2.1实现接口:对服务消费方隐藏实现
package com.hthl.provider.service.impl;import com.hthl.api.service.inf.DemoService;public class DemoServiceImpl implements DemoService {    public String sayHello(String name) {        return "Hello " + name;    }}
2.2暴露服务:在服务提供方用Spring配置声明暴露服务

在spring配置文件头部引入文件xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xsi:schemaLocation="http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"新增配置如下:<!-- dubbo配置 --><!-- 提供方应用信息,用于计算依赖关系 --> <dubbo:application name="dubbo-provider" /><!--使用zookeeper注册中心暴露服务地址 --><dubbo:registry protocol="zookeeper" address="192.168.20.38:2181,192.168.20.52:2181,192.168.20.111:2181" check="false" file="false" /><!-- 用dubbo协议在20880端口暴露服务 --><dubbo:protocol name="dubbo" port="20880" /><dubbo:provider timeout="10000"></dubbo:provider><!-- 声明需要暴露的DemoService的服务接口 --><dubbo:service interface=" com.hthl.api.service.inf.DemoService" ref="demoServiceImpl" /><bean id="demoServiceImpl" class="com.hthl.provider.service.impl.DemoServiceImpl"/>
3.服务消费方
3.1引用远程服务:在服务消费方通过Spring配置引用远程服务
在spring配置文件头部引入文件xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xsi:schemaLocation="http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"<!-- dubbo配置 --><!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 --><dubbo:application name="dubbo-consumer" /><!-- 使用zookeeper注册中心暴露服务地址 --><dubbo:registry protocol="zookeeper" address="192.168.20.38:2181,192.168.20.52:2181,192.168.20.111:2181" check="false" file="false" /><!-- 生成远程服务代理,可以像使用本地bean一样使用demoService --><dubbo:reference id="demoService" interface="com.hthl.api.service.inf.DemoService" />
3.2调用服务测试
package com.hthl.consumer.web.controller;import javax.servlet.http.HttpServletRequest;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.hthl.api.service.inf.DemoService;@Controller@RequestMapping("/demo")public class DemoController {private static final Logger logger = Logger.getLogger(DemoController.class);@Autowiredprivate DemoService demoService;@RequestMapping("/sayHello")@ResponseBodypublic String sayHello(HttpServletRequest request, Model model,String name) {logger.info("消费者测试方法!");return demoService.sayHello(name);}}

原创粉丝点击