今天就跟大家聊聊有关Dubbox服务消费方如何开发,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1、创建maven工程(打包方式为war)dubbodemo_consumer,pom.xml配置和上面服务提供者相同,只需要将Tomcat插件的端口号改为8082即可。

2、配置web.xml文件

~~~xml

<!DOCTYPE web-app PUBLIC

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

<display-name>Archetype Created Web Application</display-name>

<servlet>

<servlet-name>springmvc</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载 -->

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext-web.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>springmvc</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

~~~

3、将服务提供者工程中的HelloService接口复制到当前工程

4、编写Controller

~~~java

package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.itheima.service.HelloService;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

@RequestMapping("/demo")

public class HelloController {

@Reference

private HelloService helloService;

@RequestMapping("/hello")

@ResponseBody

public String getName(String name){

//远程调用

String result = helloService.sayHello(name);

System.out.println(result);

return result;

}

}

~~~

注意:Controller中注入HelloService使用的是Dubbo提供的@Reference注解

5、在src/main/resources下创建applicationContext-web.xml

~~~xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://code.alibabatech.com/schema/dubbo

http://code.alibabatech.com/schema/dubbo/dubbo.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 当前应用名称,用于注册中心计算应用间依赖关系,注意:消费者和提供者应用名不要一样 -->

<dubbo:application name="dubbodemo-consumer" />

<!-- 连接服务注册中心zookeeper ip为zookeeper所在服务器的ip地址-->

<dubbo:registry address="zookeeper://192.168.134.129:2181"/>

<!-- 扫描的方式暴露接口 -->

<dubbo:annotation package="com.itheima.controller" />

</beans>

~~~

6、运行测试

tomcat7:run启动

在浏览器输入http://localhost:8082/demo/hello.do?name=Jack,查看浏览器输出结果。

看完上述内容,你们对Dubbox服务消费方如何开发有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。