Dubbo basics (1): introduction and construction

Dubbo is:

  • A distributed, high-performance, and transparent RPC service framework.
  • Provide efficient service self-care solutions such as automatic registration and automatic discovery of services.
  • The main functions include: high-performance NIO communication and multi-protocol integration, service dynamic addressing and routing, soft load balancing and fault tolerance, dependency analysis and degradation, etc.

Dubbo structure and function:

  1. The container is responsible for starting, loading, and running the provider
  2. When the provider starts, register its own service with the registry
  3. When cousumer starts, subscribe its own service to the registry
  4. The registry provides a list of providers to consumers and pushes changes in real time
  5. The consumer selects a provider to call according to the load algorithm according to the provider list
  6. monitor counts the call frequency of rpc

Dubbo deployed in the project:

  1. Within an application service ( application ) , there are both external services (provider) and dependence on external services (consumer).

  2. provider涉及:registry/protocol/service/method/provider

  3. consumer涉及:registry/reference/method/consumer

  4. The information of each service interface will be reflected to the monitor . To the application which identifies the name of the application belongs.

Simply build a distributed project, and use dubbo to manage the service:

Environment dependency: zookeeper, jdk1.8, tomcat7, dubbo-admin (console)

dubbo-admin installation:

  1.     Download link: https://github.com/apache/incubator-dubbo/archive/dubbo-2.6.0.zip
  2.      Unzip and enter the dubbo-admin directory, open a command window, and enter the command mvn clean package
  3.      Unzip the war package and find the dubbo configuration file dubbo.properties to modify the zk connection address
  4.      Put this folder in tomcat's webapps directory, start tomcat
  5.      Enter localhost:8080/file name, username/password root/root

One, create a simple mvc project storePortal

In addition to introducing necessary dependencies for mvc, pom files also need to introduce dubbo related dependencies

       <dependency>
        	<groupId>com.101tec</groupId>
        	<artifactId>zkclient</artifactId>
        	<version>0.3</version>
        </dependency>
        
        <dependency>
        	<groupId>org.apache.zookeeper</groupId>
        	<artifactId>zookeeper</artifactId>
        	<version>3.4.5</version>
        </dependency>
		    
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>2.6.0</version>
			<scope>compile</scope>
			<exclusions>
				<exclusion>
					<artifactId>spring</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
			</exclusions>
         </dependency>

This module needs to be accessed by the outside world, add a tomcat plug-in, or package it and put it in tomcat

<build>
	   <plugins>
			<!-- 配置Tomcat插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<port>8080</port>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
   </build>

web.xml configuration

<?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">
  <display-name>storePortal</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- Spring MVC servlet -->
    <servlet>  
        <servlet-name>SpringMVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>

The dubbo configuration methods include XML, peoperties, annotation and api methods:

xml way:

Service provider: The xml configuration is to deliver the service class to the spring's ioc container, and dubbo will open the service as an rpc service to provide services to the outside world, so there is no need to add @Service annotations to the service class

<?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:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans.xsd
	      http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
	 http://code.alibabatech.com/schema/dubbo
	 http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <context:component-scan base-package="com.enjoy.dao"/>

    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="storeServer"/>

    <!-- 使用zookeeper注册中心暴露服务地址 -->
    <dubbo:registry address="zookeeper://192.168.244.2:2181"/>

    <!-- 用dubbo协议在20880端口暴露服务 -->
    <dubbo:protocol name="dubbo" port="20880"/>
    <dubbo:protocol name="rmi" port="21880"/>

    <!-- 
               声明需要暴露的服务接口
        dubbo把ioc容器内的service开放成rpc服务 
     -->
    <dubbo:service interface="com.enjoy.service.OrderService" ref="orderService" >
        <!-- <dubbo:method name="getDetail" cache="lru" /> -->
    </dubbo:service>

    <dubbo:service interface="com.enjoy.service.UserService" ref="userService" />
    <dubbo:service interface="com.enjoy.service.VipUserService" ref="vipUserService" />

     <!--
                 和本地bean一样实现服务 
                 把服务交给ioc容器管理
     -->
    <bean id="orderService" class="com.enjoy.service.impl.OrderServiceImpl"/>
    <bean id="userService" class="com.enjoy.service.impl.UserServiceImpl"/>
    <bean id="vipUserService" class="com.enjoy.service.impl.VipUserServiceImpl"/>

Service consumer: The xml method is to pass the referenced service to the spring's ioc container. If the service is obtained from the container, it needs to be annotated with @Autowired

<?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://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans.xsd        
	 http://code.alibabatech.com/schema/dubbo        
	 http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="enjoyStore"/>

    <!-- 使用zookeeper注册中心暴露服务地址 -->
    <dubbo:registry address="zookeeper://192.168.244.2:2181"/>

    <!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
    <dubbo:reference id="orderService" interface="com.enjoy.service.OrderService" >
    </dubbo:reference>

    <dubbo:reference id="userService" interface="com.enjoy.service.UserService"  />
    <dubbo:reference id="vipUserService" interface="com.enjoy.service.VipUserService"  />


</beans>
@Controller
public class IndexController implements ApplicationContextAware{
	 private ApplicationContext context;

	   
	    @Autowired
	    private UserService userService;

	   
	    @Autowired
	    private OrderService orderService;
}

So you can use this service.

Properties method: It is a supplement to the xml method. If there is no configuration information defined in the xml configuration, dubbo will read it from the dubbo.properties file. If the relevant information is defined in the xml, the relevant configuration of peoperties will not take effect, properties The file has the lowest level. Generally, the connection information is configured to the properties file, and this file is placed in the Resources folder, named dubbo.properties, dubbo will automatically load this file

# 应用名
dubbo.application.name=enjoyStore_properties
# 注册中心地址
dubbo.registry.address=zookeeper://192.168.244.2:2181
# 调用协议地址
dubbo.protocol.name=dubbo
dubbo.protocol.port=28080

Annotation mode configuration dubbo

Service provider: The annotation method is to add a scanning package to the xml and scan the classes under the specified package. If the @Service (this annotation is a dubbo annotation) annotation is found on the class, then the class will be handed over to spring ioc container management, and open this class as an rpc service to provide external services

<?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:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans.xsd
	      http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
	 http://code.alibabatech.com/schema/dubbo
	 http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <context:component-scan base-package="com.enjoy.dao"/>

    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="storeServer_annotation"/>

    <!-- 使用zookeeper注册中心暴露服务地址 -->
    <dubbo:registry address="zookeeper://192.168.244.2:2181"/>

    <!-- 用dubbo协议在20880端口暴露服务 -->
    <dubbo:protocol name="rmi" port="20880"/>

    <dubbo:annotation package="com.enjoy.service" />

</beans>

Service consumer: The annotation method is to specify the scan package, scan the classes under the specified package, and find out which class member variables have @Reference annotations (dubbo annotations), then the proxy service object will be injected into this class to complete the call . Spring annotations cannot be used here, dubbo annotations must be used to complete the reference

@Controller
public class IndexController implements ApplicationContextAware{
	 private ApplicationContext context;

	    @Reference
	    private UserService userService;

	    @Reference
	    private OrderService orderService;
}

API method: This method will not be used during development, but the structure of this method will look clearer and easier to learn and use

Service provider:

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.enjoy.service.VipUserService;
import com.enjoy.service.impl.VipUserServiceImpl;

import java.io.IOException;

public class StoreProvider {
    public static void main(String[] args) throws IOException {
        initDubbo();
    }

    public static void initDubbo() throws IOException {
            // 当前应用配置
            ApplicationConfig application = new ApplicationConfig();
            application.setName("StoreServerApi");

            // 连接注册中心配置
            RegistryConfig registry = new RegistryConfig();
            registry.setProtocol("zookeeper");
            registry.setAddress("192.168.244.2:2181");

            // 服务提供者协议配置
            ProtocolConfig protocol = new ProtocolConfig();
            protocol.setName("rmi");
            protocol.setPort(21880);
            protocol.setThreads(100);

            // 注意:ServiceConfig为重对象,内部封装了与注册中心的连接,以及开启服务端口
            // 服务提供者暴露服务配置
            // 此实例很重,封装了与注册中心的连接,请自行缓存,否则可能造成内存和连接泄漏
            ServiceConfig<VipUserService> service = new ServiceConfig<>();

            service.setApplication(application);
            service.setRegistry(registry); // 多个注册中心可以用setRegistries()
            service.setProtocol(protocol); // 多个协议可以用setProtocols()
            service.setInterface(VipUserService.class);
            service.setRef(new VipUserServiceImpl());

            // 暴露及注册服务
            service.export();
            System.out.println("dubbo服务开启。。。。。。。。");
            System.in.read();

    }
}

Service consumer:

import com.alibaba.dubbo.config.*;
import com.enjoy.service.VipUserService;
import java.io.IOException;

public class StoreConsumer {
    public static void main(String[] args) throws IOException {
        // 当前应用配置
        ApplicationConfig application = new ApplicationConfig();
        application.setName("StoreServerClientApi");

        // 连接注册中心配置
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol("zookeeper");
        registry.setAddress("192.168.244.2:2181");

        // 服务提供者协议配置
        ProtocolConfig protocol = new ProtocolConfig();
        protocol.setName("dubbo");
        protocol.setPort(20882);
        protocol.setThreads(100);

        // 注意:ReferenceConfig为重对象,内部封装了与注册中心的连接,以及与服务提供方的连接
        // 引用远程服务
        ReferenceConfig<VipUserService> reference = new ReferenceConfig<>(); // 此实例很重,封装了与注册中心的连接以及与提供者的连接,请自行缓存,否则可能造成内存和连接泄漏
        reference.setApplication(application);
        reference.setRegistry(registry); // 多个注册中心可以用setRegistries()
        reference.setInterface(VipUserService.class);

        // 和本地bean一样使用xxxService
        VipUserService vipUserService = reference.get(); // 注意:此代理对象内部封装了所有通讯细节,对象较重,请缓存复用
        String ret = vipUserService.getVipDetail("123");
        reference.destroy();
        System.out.println(ret);
        System.in.read();
    }
}

 

Guess you like

Origin blog.csdn.net/csdnbeyoung/article/details/91830735
Recommended