zoukankan      html  css  js  c++  java
  • Dubbo

    Dubbo应用

    集群和分布式

    集群和分布式概念

    image-20200817101138881

    • 集群:很多“人”一起 ,干一样的事。

      软件领域:一个软件,部署在多台服务器上。

      image-20200911234903849

    • 分布式:很多“人”一起干不一样的事,分工合作,就像工厂的流水线。这些不一样的事,合起来是一件大事。

      软件领域:一个大的业务系统,拆分为小的业务模块,分别部署在不同的机器上

      image-20200912000328973

    项目应用

    1. 原始项目

    image-20200817101708686

    2. 集群项目

    负载均衡是高可用网络基础架构的关键组件,通常用于将工作负载分布到多个服务器来提高网站、应用、数据库或其他服务的性能和可靠性。

    访问淘宝时,根据用户所在地区跳转到不同的机房,提高响应速度,降低单个地区服务器的压力。

    image-20200817101751942

    3. 集群分布式项目

    淘宝购物:浏览商品(商品模块)是高频操作,相对而言下订单(订单模块)是低频操作

    image-20200817101816782

    dubbo快速入门

    Dubbo作为一个RPC框架,其最核心的功能就是要实现跨网络的远程调用。

    本小节就是要创建两个应用,一个作为服务的提供方,一个作为服务的消费方。

    其中表现层(Controller)需要调用业务层(Service)完成功能:

    服务提供者:Service被Controller调用,因此被调用者Service称为服务提供者

    服务消费者:Controller发起调用(userService.save()),因此调用者Controller称为服务消费者

    业务层开发

    1. 创建maven工程dubbo-service,在pom.xml文件中导入如下坐标

      <properties>
         <spring.version>5.1.9.RELEASE</spring.version>
         <dubbo.version>2.7.4.1</dubbo.version>
         <zookeeper.version>4.0.0</zookeeper.version>
      </properties>

      <dependencies>
         <!-- servlet3.0规范的坐标 -->
         <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
             <version>3.1.0</version>
             <scope>provided</scope>
         </dependency>

         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-webmvc</artifactId>
             <version>${spring.version}</version>
         </dependency>

      </dependencies>
    2. 新建UserService和UserServiceImpl

      public interface UserService {
         String sayHello();
      }
      @Service//将该类的对象创建出来,放到Spring的IOC容器中  bean定义
      public class UserServiceImpl implements UserService {

         public String sayHello() {
             return "hello dubbo hello!~";
        }
      }
    3. 新建Spring配置文件:resourcesspringapplicationContext.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: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">

        <context:component-scan base-package="com.itheima.service" />
      </beans>

    表现层开发

    1. 新建dubbo-web模块,打包方式为war

      <packaging>war</packaging> 
      <packaging>war</packaging>

      <properties>
         <spring.version>5.1.9.RELEASE</spring.version>
         <dubbo.version>2.7.4.1</dubbo.version>
         <zookeeper.version>4.0.0</zookeeper.version>
      </properties>

      <dependencies>
         <!-- servlet3.0规范的坐标 -->
         <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
             <version>3.1.0</version>
             <scope>provided</scope>
         </dependency>
         <!--springmvc的坐标-->
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-webmvc</artifactId>
             <version>${spring.version}</version>
         </dependency>

      </dependencies>


      <build>
         <plugins>
             <!--tomcat插件-->
             <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                 <version>2.1</version>
                 <configuration>
                     <port>8000</port>
                     <path>/</path>
                 </configuration>
             </plugin>
         </plugins>
      </build>
    2. 配置SpringMVC:resourcesspringspringmvc.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:dubbo="http://dubbo.apache.org/schema/dubbo"
            xmlns:mvc="http://www.springframework.org/schema/mvc"
            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://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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">

         <mvc:annotation-driven/>
         <context:component-scan base-package="com.itheima.controller"/>
      </beans>
    3. 配置web.xml:webappWEB-INFweb.xml

      注意:配置监听器保证Tomcat启动时加载Spring配置文件:classpath*

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
              version="2.5">

      <!-- spring -->
         <context-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>classpath*:spring/applicationContext*.xml</param-value>
         </context-param>
         <listener>
             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>

      <!-- Springmvc -->
         <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:spring/springmvc.xml</param-value>
             </init-param>
         </servlet>

         <servlet-mapping>
             <servlet-name>springmvc</servlet-name>
             <url-pattern>*.do</url-pattern>
         </servlet-mapping>

      </web-app>

      注意:DispatcherServlet的第二种拦截配置方式:<url-pattern>*.do</url-pattern>

      表示只拦截URL以.do结尾的,比如http://localhost:8000/user/sayHello.do

    4. 表现层需要调用业务层,因此添加dubbo-service的依赖

      <!--依赖service模块-->
      <dependency>
         <groupId>com.itheima</groupId>
         <artifactId>dubbo-service</artifactId>
         <version>1.0-SNAPSHOT</version>
      </dependency>
    5. 编写UserController

      @RestController
      @RequestMapping("/user")
      public class UserController {

         //注入Service
         @Autowired//本地注入
         private UserService userService;

         @RequestMapping("/sayHello")
         public String sayHello(){
             return userService.sayHello();
        }

      }

       

    安装dubbo-service到本地仓库

    image-20201209130048761

    1. 启动dubbo-web:使用tomcat7-maven插件

    2. 访问http://localhost:8000/user/sayHello.do

     

    服务提供者(重点)

    在dubbo-service工程中完成如下改动:

    1. 添加Dubbo、注册中心Zookeeper和log4j的坐标

      在Maven中自定义属性:

      <properties>
         <spring.version>5.1.9.RELEASE</spring.version>
         <dubbo.version>2.7.4.1</dubbo.version>
         <zookeeper.version>4.0.0</zookeeper.version>
      </properties>

      添加依赖

      <!--Dubbo的起步依赖,版本2.7之后统一为org.apache.dubbo -->
      <dependency>
         <groupId>org.apache.dubbo</groupId>
         <artifactId>dubbo</artifactId>
         <version>${dubbo.version}</version>
      </dependency>
      <!--ZooKeeper客户端实现 -->
      <dependency>
         <groupId>org.apache.curator</groupId>
         <artifactId>curator-framework</artifactId>
         <version>${zookeeper.version}</version>
      </dependency>
      <!--ZooKeeper客户端实现 -->
      <dependency>
         <groupId>org.apache.curator</groupId>
         <artifactId>curator-recipes</artifactId>
         <version>${zookeeper.version}</version>
      </dependency>

      <!--日志-->
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>1.7.21</version>
      </dependency>
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
         <version>1.7.21</version>
      </dependency>
    2. 新建日志配置文件:resourceslog4j.properties

      # DEBUG < INFO < WARN < ERROR < FATAL
      # Global logging configuration
      log4j.rootLogger=info, stdout,file
      # My logging configuration...
      #log4j.logger.com.tocersoft.school=DEBUG
      #log4j.logger.net.sf.hibernate.cache=debug
      ## Console output...
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
      log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

      log4j.appender.file=org.apache.log4j.FileAppender
      log4j.appender.file.File=../logs/iask.log
      log4j.appender.file.layout=org.apache.log4j.PatternLayout
      log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %m%n
    3. 修改UserServiceImpl中的注解

      注意:服务实现类上使用的Service注解是Dubbo提供的,用于对外发布服务

      import org.apache.dubbo.config.annotation.Service;
      @Service//将这个类提供的方法(服务)对外发布。将访问的地址 ip,端口,路径注册到注册中心中
      public class UserServiceImpl implements UserService {

         public String sayHello() {
             return "hello dubbo hello!~";
        }
      }
    4. 在dubbo-service工程中配置dubbo信息:src/main/resources/applicationContext.xml

      • 确保引入dubbo命名空间

        <?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: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">
        </beans>
      • 配置应用名称,注册中心zk地址,dubbo包扫描

        <!--dubbo的配置-->
        <!--1.配置项目的名称,唯一-->
        <!-- 当前应用名称,用于注册中心计算应用间依赖关系,注意:消费者和提供者应用名不要一样 -->
        <dubbo:application name="dubbo-service"/>
        <!--2.配置注册中心的地址-->
        <!-- 连接服务注册中心zookeeper ip为zookeeper所在服务器的ip地址-->
        <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
        <!--3.配置dubbo包扫描-->
        <dubbo:annotation package="com.itheima.service.impl" />
    5. 将模块改为web工程 -> 修改dubbo-service的pom.xml:打包为war,添加tomcat7插件

      注意:改造之后UserController通过网络访问UserService,因此需要保证dubbo-service项目一直启动

      <packaging>war</packaging>

      配置tomcat7-maven插件

      <build>
          <plugins>
              <!--tomcat插件-->
              <plugin>
                  <groupId>org.apache.tomcat.maven</groupId>
                  <artifactId>tomcat7-maven-plugin</artifactId>
                  <version>2.1</version>
                  <configuration>
                      <port>8002</port>
                      <path>/</path>
                  </configuration>
              </plugin>
          </plugins>
      </build>
    6. 在srcmain目录下添加webappWEB-INFweb.xml,保留Spring提供的监听器

      作用:负责Tomcat启动时加载dubbo相关的配置

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns="http://java.sun.com/xml/ns/javaee"
               xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
               version="2.5">
      
         <!-- spring -->
          <context-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>classpath*:spring/applicationContext*.xml</param-value>
          </context-param>
          <listener>
              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          </listener>
      
      </web-app>
    7. 启动测试:tomcat7:run,启动后自动注册UserService服务到Zookeeper中

       

    服务消费者(重点)

    在dubbo-web工程中完成如下改动:

    1. 将UserService接口提取到dubbo-interface模块中

      注意:dubbo-service和dubbo-web中都需要使用UserService类,因此单独将UserService接口拆分到dubbo-interface模块

    2. dubbo-service和dubbo-web的pom.xml中引入dubbo-interface,并对dubbo-interface执行install

      <!--依赖公共的接口模块-->
      <dependency>
          <groupId>com.itheima</groupId>
          <artifactId>dubbo-interface</artifactId>
          <version>1.0-SNAPSHOT</version>
      </dependency>
    3. 添加Dubbo、Zookeeper和日志的引用和日志配置文件log4j.properties

      <!--Dubbo的起步依赖,版本2.7之后统一为org.apache.dubbo -->
      <dependency>
          <groupId>org.apache.dubbo</groupId>
          <artifactId>dubbo</artifactId>
          <version>${dubbo.version}</version>
      </dependency>
      <!--ZooKeeper客户端实现 -->
      <dependency>
          <groupId>org.apache.curator</groupId>
          <artifactId>curator-framework</artifactId>
          <version>${zookeeper.version}</version>
      </dependency>
      <!--ZooKeeper客户端实现 -->
      <dependency>
          <groupId>org.apache.curator</groupId>
          <artifactId>curator-recipes</artifactId>
          <version>${zookeeper.version}</version>
      </dependency>
      
      <!--日志-->
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.21</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.21</version>
      </dependency>
    4. 在dubbo-web工程中添加Dubbo配置:src/main/resources/spring/springmvc.xml

      <!--dubbo的配置-->
      <!--1.配置项目的名称,唯一-->
      <!-- 当前应用名称,用于注册中心计算应用间依赖关系,注意:消费者和提供者应用名不要一样 -->
      <dubbo:application name="dubbo-web" >
          <!-- dubbo监控使用的端口-->
          <dubbo:parameter key="qos.port" value="33333"/>
      </dubbo:application>
      <!--2.配置注册中心的地址-->
      <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
      <!--3.配置dubbo包扫描-->
      <!-- 包扫描的方式 引用服务 扫描@Reference -->
      <dubbo:annotation package="com.itheima.controller" />
    5. 修改UserController

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

      import org.apache.dubbo.config.annotation.Reference;
      @RestController
      @RequestMapping("/user")
      public class UserController {
      
          /*
              1. 从zookeeper注册中心获取userService的访问url
              2. 进行远程调用RPC
              3. 将结果封装为一个代理对象。给变量赋值
           */
          @Reference//远程注入
          private UserService userService;
      
      
          @RequestMapping("/sayHello")
          public String sayHello(){
              return userService.sayHello();
          }
      
      }
    6. 启动dubbo-service和dubbo-web测试:tomcat7:run http://localhost:8000/user/sayHello.do

     

    序列化

    1. dubbo 内部已经封装序列化和反序列化的过程

    2. 我们只需要在定义pojo类时实现Serializable接口即可

    3. 一般会定义一 个公共的pojo模块,让生产者和消费者都依赖该模块。

    1581317650919

    1. 新建dubbo-pojo模块,添加User实体类

      /**
       * 注意!!!
       *  将来所有的pojo类都需要实现Serializable接口
       */
      public class User implements Serializable {
          private int id;
          private String username;
          private String password;
      
          public User() {
          }
      
          public User(int id, String username, String password) {
              this.id = id;
              this.username = username;
              this.password = password;
          }
      
          public int getId() {
              return id;
          }
      
          public void setId(int id) {
              this.id = id;
          }
      
          public String getUsername() {
              return username;
          }
      
          public void setUsername(String username) {
              this.username = username;
          }
      
          public String getPassword() {
              return password;
          }
      
          public void setPassword(String password) {
              this.password = password;
          }
      }
    2. 在dubbo-interface模块的UserService接口中添加findUserById方法,并添加dubbo-pojo依赖

      <dependency>
          <groupId>com.itheima</groupId>
          <artifactId>dubbo-pojo</artifactId>
          <version>1.0-SNAPSHOT</version>
      </dependency>
      public interface UserService {
      
          public String sayHello();
      
          /**
           * 查询用户
           */
          public User findUserById(int id);
      }
    3. 对dubbo-pojo, dubbo-interface执行instal,将最新jar包安装到本地Maven仓库

    4. 在dubbo-service模块的UserServiceImpl中添加findUserById方法实现

      public User findUserById(int id) {
          //查询User对象
          User user = new User(1,"zhangsan","123"); //模拟从数据库查询用户信息
          return user;
      }
    5. 在dubbo-web模块的UserController中远程调用findUserById方法

      /**
       * 根据id查询用户信息
       * @param id
       * @return
       */
      //http://localhost:8000/user/find.do?id=3
      @RequestMapping("/find")
      public User find(int id){
          return userService.findUserById(id);
      }
    6. 启动dubbo-service和dubbo-web

    易错点:User对象未实现serializable接口

     

    超时

    • 服务消费者在调用服务提供者的时候发生了阻塞、等待的情形,这个时候,服务消费者会直等待下去。

    • 在某个峰值时刻,大量的请求都在同时请求服务消费者,会造成线程的大量堆积,势必会造成雪崩。

    • dubbo利用超时机制来解决这个问题:设置一个超时时间, 在这个时间段内,无法完成服务则自动断开连接。

    • 使用timeout属性配置超时时间,默认值1000,单位毫秒

      //timeout 超时时间 单位毫秒  retries 重试次数
      @Service(timeout = 3000,retries=0)

      注意:超时时间建议配置在服务提供方

    演示效果:

    1. 模拟查询用户超时:UserServiceImpl

      @Service(timeout = 3000, retries = 0)//当前服务3秒超时
      public class UserServiceImpl implements UserService {
      
          public String sayHello() {
              return "hello dubbo hello!~";
          }
      
          public User findUserById(int id) {
              //查询User对象
              User user = new User(1, "zhangsan", "123");
      
              try {
                  //数据库查询很慢,查了5秒
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              return user;
          }
      }
    2. 查看是否3秒超时抛出异常:UserController

      @RestController
      @RequestMapping("/user")
      public class UserController {
      
          @Reference //远程注入
          private UserService userService;
      
          @RequestMapping("/sayHello")
          public String sayHello() {
              return userService.sayHello();
          }
      
          /**
           * 根据id查询用户信息
           *
           * @param id
           * @return
           */
          int i = 1;
      
          @RequestMapping("/find")
          public User find(int id) {
              new Thread(new Runnable() {
                  public void run() {
                      while (true) {
                          System.out.println(i++);
                          try {
                              Thread.sleep(1000);
                          } catch (InterruptedException e) {
                              e.printStackTrace();
                          }
                      }
                  }
              }).start();
      
              return userService.findUserById(id);
          }
      
      }
    3. 访问http://localhost:8000/user/find.do?id=1

    重试

    1. 设置了超时时间,在这个时间段内,无法完成服务访问,则自动断开连接。

    2. 如果出现网络抖动,则这一次请求就会失败。

    3. Dubbo提供重试机制来避免类似问题的发生。

    4. 通过retries属性来设置重试次数。默认为2次

      //timeout:超时时间(单位毫秒),  retries:重试次数
      @Service(timeout = 3000, retries=3)

    多版本

    灰度发布:当出现新功能时,会让一部分用户先使用新功能,用户反馈没问题时,再将所有用户迁移到新功能。

    dubbo中使用version属性来设置和调用同一个接口的不同版本

    服务提供者dubbo-service配置:

    @Service(version="v2.0")
    public class UserServiceImp12 implements UserService {...}

    消费者dubbo-web配置:

    @Reference(version = "v2.0")//远程注入
    private UserService userService;

     

  • 相关阅读:
    机器学习三--分类--邻近取样(Nearest Neighbor)
    机器学习二——分类算法--决策树DecisionTree
    机器学习一--基本概念
    python学习--常用正则表达式整理
    python学习--字符编码问题
    python学习--字符串处理相关方法
    python学习--如何在一个for循环中迭代多个可迭代对象(串行,并行)
    python学习--如何对迭代器进行切片操作
    List对象去重
    List 简单升降序实现
  • 原文地址:https://www.cnblogs.com/sunhao410526/p/14559330.html
Copyright © 2011-2022 走看看