使用Dubbo实现简单的RPC调用(Spring配置文件版)


更多文章和资源欢迎访问:SuperCoder Blog


文章目录

  • 更多文章和资源欢迎访问:[SuperCoder Blog](https://supercoder.com.cn)
  • 前言
  • 一、Dubbo架构
  • 二、安装zookeeper
  • 三、代码实战
    • 1. 创建服务提供方
    • 2. 创建服务消费方
  • 四、服务调用


前言

Dubbo是阿里巴巴公司开源(已捐献给Apache)的高性能、轻量级的Java RPC框架。致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案。

官网:Dubbo中文官网


一、Dubbo架构

使用Dubbo实现简单的RPC调用(Spring配置文件版)_第1张图片

二、安装zookeeper

下载地址:https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/

上传到服务器

# mac 终端上传,可以使用其他工具
scp /Users/chaishuai/Downloads/apache-zookeeper-3.6.3-bin.tar.gz [email protected]:/usr/local/

解压并重命名

# 解压
tar -zxvf apache-zookeeper-3.6.3-bin.tar.gz 
# 重命名
mv apache-zookeeper-3.6.3-bin zookeeper

修改配置文件

# 进入配置文件目录
cd /usr/local/zookeeper/conf/
# 因为zookeeper配置文件要叫zoo.cfg,所以复制一份zoo_sample.cfg
cp zoo_sample.cfg zoo.cfg
# 切换到zookeeper目录下,创建zookeeper数据目录
cd /usr/local/zookeeper
mkdir data
# 修改zoo.cfg
vim zoo.cfg
# 修改dataDir=/tmp/zookeeper 为 /usr/local/zookeeper/data

启动zookeeper

# 进入bin目录
cd /usr/local/zookeeper/bin
# 启动zookeeper
./zkServer.sh start
# 查看状态
./zkServer.sh status
# 停止zookeeper
./zkServer.sh stop

注意:zookeeper启动默认会使用8080端口,如果启动后查看状态显示失败,检查8080端口是否被占用。如果被占用可根据实际情况修改。

三、代码实战

1. 创建服务提供方

创建maven web工程dubbo-provider,引入相关依赖



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>cn.com.supercodergroupId>
  <artifactId>dubbo-providerartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>dubbo-provider Maven Webappname>
  <url>https://www.supercoder.com.cnurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <dubbo.version>2.7.15dubbo.version>
    <zookeeper.version>3.4.6zookeeper.version>
    <spring.version>5.2.9.RELEASEspring.version>
  properties>

  <dependencies>
  
    <dependency>
      <groupId>cn.com.supercodergroupId>
      <artifactId>dubbo-entityartifactId>
      <version>1.0-SNAPSHOTversion>
    dependency>
    
    <dependency>
      <groupId>cn.com.supercodergroupId>
      <artifactId>dubbo-interfaceartifactId>
      <version>1.0-SNAPSHOTversion>
    dependency>
    
    <dependency>
      <groupId>org.apache.dubbogroupId>
      <artifactId>dubboartifactId>
      <version>${dubbo.version}version>
    dependency>
    
    <dependency>
      <groupId>org.apache.zookeepergroupId>
      <artifactId>zookeeperartifactId>
      <version>${zookeeper.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.curatorgroupId>
      <artifactId>curator-recipesartifactId>
      <version>4.2.0version>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
  dependencies>
  <build>
    <finalName>dubbo-providerfinalName>
    <pluginManagement>
      <plugins>
      	
          <plugin>
            <groupId>org.apache.tomcat.mavengroupId>
            <artifactId>tomcat7-maven-pluginartifactId>
            <version>2.1version>
            <configuration>
              <port>9001port>
              <path>/path>
            configuration>
          plugin>
      plugins>
    pluginManagement>
  build>
project>

服务提供方要提供的方法

/**
 * @desc UserService实现类
 * @author supercoder
 */
public class UserServiceImpl implements UserService {

    @Override
    public List<User> getUserList() {
        // 此处模拟返回UserList
        ArrayList<User> list = new ArrayList<>();
        User userA = new User();
        userA.setUuid(UUID.randomUUID().toString().replace("-",""));
        userA.setAge("V1.0.0");
        userA.setUsername("SuperCoderBlog");
        userA.setAddress("https://www.supercoder.com.cn");
        User userB = new User();
        userB.setUuid(UUID.randomUUID().toString().replace("-", ""));
        userB.setAge("V1.0.0");
        userB.setUsername("SuperCoderBbs");
        userB.setAddress("https://bbs.supercoder.com.cn");
        list.add(userA);
        list.add(userB);
        return list;
    }
}

创建Spring配置文件并配置要暴露的服务


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    
    <dubbo:application name="dubbo-provider"/>

    
    <dubbo:registry address="zookeeper://xxx.xxx.xxx.xxx:2181"/>

    
    <dubbo:protocol name="dubbo" port="20881"/>

    
    <dubbo:service interface="cn.com.supercoder.service.UserService" ref="userService"/>

    
    <bean id="userService" class="cn.com.supercoder.service.impl.UserServiceImpl"/>

beans>

在web.xml中配置监听器加载Spring配置文件

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 Applicationdisplay-name>
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:provider.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
web-app>

2. 创建服务消费方

创建maven web工程dubbo-consumer,引入相关依赖



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>cn.com.supercodergroupId>
  <artifactId>dubbo-consumerartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>dubbo-consumer Maven Webappname>
  <url>https://www.supercoder.com.cnurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <dubbo.version>2.7.15dubbo.version>
    <zookeeper.version>3.4.6zookeeper.version>
    <spring.version>5.2.9.RELEASEspring.version>
  properties>

  <dependencies>
  	
    <dependency>
      <groupId>cn.com.supercodergroupId>
      <artifactId>dubbo-entityartifactId>
      <version>1.0-SNAPSHOTversion>
    dependency>
	
    <dependency>
      <groupId>cn.com.supercodergroupId>
      <artifactId>dubbo-interfaceartifactId>
      <version>1.0-SNAPSHOTversion>
    dependency>
	
    <dependency>
      <groupId>org.apache.dubbogroupId>
      <artifactId>dubboartifactId>
      <version>${dubbo.version}version>
    dependency>
	
    <dependency>
      <groupId>org.apache.zookeepergroupId>
      <artifactId>zookeeperartifactId>
      <version>${zookeeper.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.curatorgroupId>
      <artifactId>curator-recipesartifactId>
      <version>4.2.0version>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
  dependencies>

  <build>
    <finalName>dubbo-consumerfinalName>
    <pluginManagement>
      <plugins>
      	
        <plugin>
          <groupId>org.apache.tomcat.mavengroupId>
          <artifactId>tomcat7-maven-pluginartifactId>
          <version>2.1version>
          <configuration>
            <port>7001port>
            <path>/path>
          configuration>
        plugin>
      plugins>
    pluginManagement>
  build>
project>

创建Service调用服务提供方提供的UserService服务

/**
 * @author supercoder
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserService userService;

    @Override
    public List<User> getUserList() {
        return userService.getUserList();
    }
}

创建Controller调用Service实现业务调用

/**
 * @author supercoder
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("/getAll")
    @ResponseBody
    public List<User> getUserList(){
        List<User> userList = orderService.getUserList();
        return userList;
    }
}

创建Spring配置文件引用服务


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

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

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

    
    <dubbo:reference id="userService" interface="cn.com.supercoder.service.UserService"/>
    
	
    <context:component-scan base-package="cn.com.supercoder.service"/>

beans>

创建SpringMVC配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="cn.com.supercoder.controller"/>

    
    <mvc:annotation-driven/>

beans>

在web.xml中配置加载Spring和SpringMVC配置文件

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 Applicationdisplay-name>

  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:consumer.xmlparam-value>
  context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/*url-pattern>
  servlet-mapping>
web-app>

四、服务调用

完成服务提供方和消费方的创建后,启动两个工程,测试调用。

注意事项

  1. zookeeper服务正常启动
  2. 因为服务调用结果需要序列化后通过网络传输,所以实体类必须实现Serializable接口
  3. 实体类模块和接口模块的代码比较简单,本文省略,需要自行创建

访问 http://localhost:7001/order/getAll 测试

测试结果:
使用Dubbo实现简单的RPC调用(Spring配置文件版)_第2张图片
至此,一个通过Spring配置文件方式实现的Dubbo RPC调用demo就完成了。

你可能感兴趣的:(Dubbo,rpc,zookeeper)