I heard that wechat search “Java fish” will change strong!

This article is in Java Server, which contains my complete series of Java articles, can be read for study or interview

Dubbo is needed in recent projects. Although I know that Dubbo is an RPC framework, I did not get to know it in detail. Since the project is to be used, it is necessary to learn the application of Dubbo first, and then to understand the internal principles of Dubbo after skilled use. If you want the project code, just contact me. If you want demo code, just contact me.

(A) What is Dubbo

At present, Dubbo is the most famous RPC service invocation framework. It is an SOA service governance framework of Ali open source, which has relatively complete functions and supports a variety of transmission and serialization schemes. The most common use of Dubbo is for remote calls.

There are four core objects on the server side of Dubbo:

ApplicationConfig: Configures the current application information

ProtocolConfig: Configures the service protocol information

RegistryConfig: Configures registration information

ServiceConfig: Configure exposed service information

There are two core objects in the Dubbo client:

ApplicationConfig: Configures the current application information

ReferenceConfig: Configures the referenced service information

(2) Dubbo

There are three ways to get started with Dubbo. The direct connection and registry implementation of Dubbo will be shown directly in code, followed by the use of Spring and SpringBoot, respectively.

Before writing the Dubbo code, we need to define a common client service that houses the Service interface. Service providers introduce the project, write implementation classes, and provide the Dubbo interface; The service consumer is introduced into the project and invoked through the service interface of the project.

Therefore, create such a module, named dubo-client, the overall code structure is as follows, only need to write a service interface:

The User class:

@Data
public class User implements Serializable {
    private static final long serialVersionUID = -9206514891359830486L;
    private Long id;
    private String name;
    private String sex;
}
Copy the code

UserService:

public interface UserService {
    User getUser(Long id);
}
Copy the code

2.1 Direct Code

Next, generate a dubbo service in direct code and call the dubbo service with another class:

2.1.1 Introducing dependencies

There are only two core dependencies, a dubbo dependency and a public interface method above it

<dependencies>
    <dependency>
        <groupId>org.apache.dubbo</groupId>
        <artifactId>dubbo</artifactId>
        <version>2.74.1.</version>
    </dependency>
    <dependency>
        <artifactId>dubbo-client</artifactId>
        <groupId>com.javayz</groupId>
        <version>0.01.-SNAPSHOT</version>
    </dependency>
</dependencies>
Copy the code

2.1.2 Writing a service provider

The service provider mainly configures the following properties:

1. Application: Set the application name and other information

2. Protocol: Sets the protocol of the service

3. Register: Set the connection mode of the service

4. Service: Register the services to be exposed

public class DubboProvider {
    public static void main(String[] args) throws IOException {
        // Expose the UserService service
        / / 1, the application
        ApplicationConfig applicationConfig=new ApplicationConfig("sample-provider");
        //2. Protocol -dubbo
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("dubbo");
        protocolConfig.setPort(20880);
        / / 3, the register
        // Direct connection without exposure to the registry
        RegistryConfig registryConfig=new RegistryConfig(RegistryConfig.NO_AVAILABLE);
        / / 4, the service
        ServiceConfig serviceConfig=new ServiceConfig();
        serviceConfig.setInterface(UserService.class);
        serviceConfig.setRef(new UserServiceImpl());
        // Register application, protocol, and register with service
        serviceConfig.setRegistry(registryConfig);
        serviceConfig.setProtocol(protocolConfig);
        serviceConfig.setApplication(applicationConfig);
        serviceConfig.export();

        System.out.println("Service has been exposed."); System.in.read(); }}Copy the code

2.1.3 Write service consumers

There are three main steps for the realization of consumers:

1. Configure application: Set the application name and other information

2. Configuration Reference: Mainly configures the information to be referenced

3. Get the interface and invoke the service.

public class DubboConsumer {
    public static void main(String[] args) {
        / / 1, the application
        ApplicationConfig applicationConfig=new ApplicationConfig("sample-consumer");
        //2. Configure reference
        ReferenceConfig referenceConfig=new ReferenceConfig();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setInterface(UserService.class);
        referenceConfig.setUrl("Dubbo: / / 172.18.2.49:20880 / com. Javayz. The client. The service. The UserService? Anyhost = true&application = sample&bind. IP = 172.18.2.49 & bind. The port = 20880 & deprecated = false&dubbo = 2.0.2 & dynamic = true&generic = fa Lse&interface = com. Javayz. Client. Service. UserService&methods = getUser&pid = 5936 & release 2.7.4.1 & side of = = provider&timestamp = 161 8036935244");
        UserService userService = (UserService) referenceConfig.get();
        User user = userService.getUser(1L); System.out.println(user); }}Copy the code

Start the provider first, then the consumer, and if the User information is printed, the call is successful.

The Register here is directly connected. We can also use the registry. Here we take ZooKeeper as an example. Start by introducing ZooKeeper-related dependencies in your project:

<! Zk client dependencies: curator --> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.13. 0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>2.13. 0</version>
</dependency>
Copy the code

The service provider modifies RegistryConfig to the ZooKeeper connection mode at one point

//register
// Direct connection without exposure to the registry
//RegistryConfig registryConfig=new RegistryConfig(RegistryConfig.NO_AVAILABLE);
// Expose Dubbo through the registry
RegistryConfig registryConfig=new RegistryConfig(Zookeeper: / / 192.168.78.128: "2181");
Copy the code

The consumer also modified a position and replaced the setUrl method in referenceConfig with ZooKeeper:

RegistryConfig registryConfig=new RegistryConfig(Zookeeper: / / 192.168.78.128: "2181");
ReferenceConfig referenceConfig=new ReferenceConfig();
referenceConfig.setRegistry(registryConfig);
referenceConfig.setApplication(applicationConfig);
referenceConfig.setInterface(UserService.class);
/ / referenceConfig. SetUrl (" dubbo: / / 172.18.2.49:20880 / com. Javayz. The client. The service. The UserService? Anyhost = true&application = sample&bind. IP = 172.18.2.49 & bind. The port = 20880 & deprecated = false&dubbo = 2.0.2 & dynamic = true&generic = fa Lse&interface = com. Javayz. Client. Service. UserService&methods = getUser&pid = 5936 & release 2.7.4.1 & side of = = provider&timestamp = 161 8036935244 ");
Copy the code

2.2 through the Spring

The Spring approach simply takes the Java code above and puts it in the configuration file, injects the interface into the Bean container, and creates two new configuration files under the Resource folder: provider.xml


      
<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-4.3.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    <! -- Provider application information for calculating dependencies -->
    <dubbo:application name="sample-provider"  />

    <! Expose the service address using the ZooKeeper broadcast registry -->
    <dubbo:registry address=Zookeeper: / / 192.168.78.128: "2181" />

    <! Expose service on port 20880 with dubbo
    <dubbo:protocol name="dubbo" port="20880" />

    <! Declare the service interface to be exposed -->
    <dubbo:service interface="com.javayz.client.service.UserService" ref="userService" />

    <! Implement the service as a local bean
    <bean id="userService" class="com.javayz.example1.service.impl.UserServiceImpl" />
</beans>
Copy the code

consumer.xml

<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-4.3.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    <dubbo:application name="sample-consumer"  />
    <dubbo:registry address=Zookeeper: / / 192.168.78.128: "2181" />
    <dubbo:reference id="userService" interface="com.javayz.client.service.UserService" />
</beans>
Copy the code

The configuration file here corresponds exactly to the code above. Next comes the provider and consumer of the service: SpringDubboProvider

public class SpringDubboProvider {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("provider.xml");
        System.out.println("Service has been exposed."); System.in.read(); }}Copy the code

SpringDubboConsumer

public class SpringDubboConsumer {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("consumer.xml");
        UserService bean = context.getBean(UserService.class);
        System.out.println(bean.getUser(1L)); }}Copy the code

2.3 SpringBoot Mode

Create two New SpringBoot projects, one service provider and one service consumer, introducing dubbo’s core dependencies

<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.4.1</version>
</dependency>
Copy the code

The configuration here is written in application.properties, starting with the service provider:

dubbo.application.name=dubbo-provider
dubbo.registry.address=zookeeper:/ / 192.168.78.128:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
Copy the code

The Service provider needs to write the implementation class of the Service. Note that the @service annotation is under the Dubbo package:

import com.javayz.client.entity.User;
import com.javayz.client.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

@Service
@Component
public class UserServiceImpl implements UserService {
    @Override
    public User getUser(Long id) {
        User user=new User();
        user.setId(id);
        user.setName("javayz");
        user.setSex("man");
        returnuser; }}Copy the code

Then add an @enabledubbo annotation to the startup class.

The consumer of the service also writes the configuration file first:

server.port=8081
dubbo.application.name=dubbo-consumer
dubbo.registry.address=zookeeper:/ / 192.168.78.128:2181
Copy the code

The Service object is then imported via the @Reference annotation

@SpringBootApplication
public class SpringbootconsumerApplication {

    @Reference
    UserService userService;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootconsumerApplication.class, args);
    }

    @Bean
    public ApplicationRunner getBean(a){
        return args -> {
            System.out.println(userService.getUser(1L)); }; }}Copy the code

(3) Common configuration of Dubbo

<dubbo:application/> Used to configure information about the current application. <dubbo:register/> Used to configure information about the connection registration. <dubbo:protocol/> Used to configure information about the protocol that provides the service. The consumer passively accepts <dubbo:service/> to expose a service, a service can be exposed with multiple protocols, A service can be registered to multiple registries. <dubbo: Provider /> When the ProtocolConfig and ServiceConfig properties are not configured, The default <dubbo:reference/> is used to create a remote service proxy when the ReferenceConfig attribute is not configuredCopy the code

More specific configuration information is found on the official website for your reference:

Dubbo.apache.org/zh/docs/v2….

(4) how to realize distributed call through DuBBo in the enterprise

In an enterprise, if a consumer invokes a provider directly through RPC, the provider’s entire Jar package theoretically needs to be introduced into the project. However, other extraneous code such as service provision can also be introduced, leading to code contamination.

Therefore, during actual development, a layer of Client modules will be added between the service provider and the caller. The Client mainly writes the interface definition of Service, the return instance object of the interface and the request instance object of the interface. In short, all the definition is done in the Client.

When used, the service provider imports the Client, writes the implementation method, and the service consumer imports the Client and invokes it directly via Dubbo.

In addition, in enterprise development, there may be multiple interface implementations. In this case, you can set groups and versions for services to distinguish them.

(5) Summary

These are the basic uses of Dubbo. Dubbo is, after all, just an RPC tool that can be used to easily expose and consume services. But two hours is only for manual use, some of its internal configuration, some of the concepts and the most important principles are to be deeply explored by ourselves. I’m fish boy. See you next time!