dubbo(一)

1. Introduction

参考链接:https://www.baeldung.com/dubbo

Dubbo is an open-source RPC and microservice framework from Alibaba.

Among other things, it helps enhance service governance and makes it possible for a traditional monolith applications to be refactored smoothly to a scalable distributed architecture.

In this article, we’ll give an introduction to Dubbo and its most important features.

dubbo 应用的是对SPI技术的拓展:http://dubbo.apache.org/zh-cn/docs/source_code_guide/dubbo-spi.html

2. Architecture

Dubbo distinguishes a few roles:

  1. Provider – where service is exposed; a provider will register its service to registry
  2. Container – where the service is initiated, loaded and run
  3. Consumer – who invokes remote services; a consumer will subscribe to the service needed in the registry
  4. Registry – where service will be registered and discovered
  5. Monitor – record statistics for services, for example, frequency of service invocation in a given time interval

Connections between a provider, a consumer and a registry are persistent, so whenever a service provider is down, the registry can detect the failure and notify the consumers.

The registry and monitor are optional. Consumers could connect directly to service providers, but the stability of the whole system would be affected.

3. Maven Dependency

Before we dive in, let’s add the following dependency to our pom.xml:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <version>2.5.7</version>
</dependency>

4. Bootstrapping

Now let’s try out the basic features of Dubbo.

This is a minimally invasive framework, and lots of its features depend on external configurations or annotations.

It’s officially suggested that we should use XML configuration file because it depends on a Spring container (currently Spring 4.3.10).

We’ll demonstrate most of its features using XML configuration.

4.1. Multicast Registry – Service Provider

As a quick start, we’ll only need a service provider, a consumer and an “invisible” registry. The registry is invisible because we are using a multicast network.

In the following example, the provider only says “hi” to its consumers:

public interface GreetingsService {
    String sayHi(String name);
}
 
public class GreetingsServiceImpl implements GreetingsService {
 
    @Override
    public String sayHi(String name) {
        return "hi, " + name;
    }
}

 

4.2. Multicast Registry – Service Registration

Let’s now register GreetingsService to the registry. A very convenient way is to use a multicast registry if both providers and consumers are on the same local network provider-app.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://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="demo-provider" version="1.0"/>
    <dubbo:registry address="multicast://224.1.1.1:9090"/>
    <dubbo:protocol name="dubbo" port="20880"/>
    <bean id="greetingsService" class="dubbo.test.app.GreetingsServiceImpl"/>
    <dubbo:service interface="dubbo.test.app.GreetingsService"
      ref="greetingsService"/>
</beans>

With the beans configuration above, we have just exposed our GreetingsService to an url under dubbo://127.0.0.1:20880 and registered the service to a multicast address specified in <dubbo:registry />.

In the provider’s configuration, we also declared our application metadata, the interface to publish and its implementation respectively by <dubbo:application /><dubbo:service />and <beans />.

The dubbo protocol is one of many protocols the framework supports. It is built on top of the Java NIO non-blocking feature and it’s the default protocol used.

We’ll discuss it in more detail later in this article.

4.3. Multicast Registry – Service Consumer

Generally, the consumer needs to specify the interface to invoke and the address of remote service, and that’s exactly what’s needed for a consumer(consumer-app.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://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="demo-consumer" version="1.0"/>
    <dubbo:registry address="multicast://224.1.1.1:9090"/>
    <dubbo:reference interface="dubbo.test.app.GreetingsService"
      id="greetingsService"/>
</beans>

Now everything’s set up, let’s see how they work in action:

public class MulticastRegistryTest
{
    @Before
    public void initRemote()
    {
        ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext(
                "resources/provider-app.xml");
        remoteContext.start();
    }

    @Test
    public void givenProvider_whenConsumerSaysHi_thenGotResponse()
    {
        ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext(
                "resources/consumer-app.xml");
        localContext.start();
        GreetingsService greetingsService = (GreetingsService) localContext
                .getBean("greetingsService");
        String hiMessage = greetingsService.sayHi("baeldung");
        assertNotNull(hiMessage);
        assertEquals("hi, baeldung", hiMessage);
    }

}

When the provider’s remoteContext starts, Dubbo will automatically load GreetingsServiceand register it to a given registry. In this case, it’s a multicast registry.

The consumer subscribes to the multicast registry and creates a proxy of GreetingsService in the context. When our local client invokes the sayHi method, it’s transparently invoking a remote service.

We mentioned that the registry is optional, meaning that the consumer could connect directly to the provider, via the exposed port:

<dubbo:reference interface="com.baeldung.dubbo.remote.GreetingsService"
  id="greetingsService" url="dubbo://127.0.0.1:20880"/>

Basically, the procedure is similar to traditional web service, but Dubbo just makes it plain, simple and lightweight.

5. Result Caching

  Natively remote result caching is supported to speed up access to hot data. It’s as simple as adding a cache attribute to the bean reference:

<dubbo:reference interface="com.baeldung.dubbo.remote.GreetingsService"
  id="greetingsService" cache="lru" />

Here we configured a least-recently-used cache. To verify the caching behavior, we’ll change a bit in the previous standard implementation (let’s call it “special implementation”):

public class GreetingsServiceSpecialImpl implements GreetingsService {
    @Override
    public String sayHi(String name) {
        try {
            SECONDS.sleep(5);
        } catch (Exception ignored) { }
        return "hi, " + name;
    }
}

After starting up provider, we can verify on the consumer’s side, that the result is cached when invoking more than once:

@Test
public void givenProvider_whenConsumerSaysHi_thenGotResponse() {
    ClassPathXmlApplicationContext localContext
      = new ClassPathXmlApplicationContext("multicast/consumer-app.xml");
    localContext.start();
    GreetingsService greetingsService
      = (GreetingsService) localContext.getBean("greetingsService");
 
    long before = System.currentTimeMillis();
    String hiMessage = greetingsService.sayHi("baeldung");
 
    long timeElapsed = System.currentTimeMillis() - before;
    assertTrue(timeElapsed > 5000);
    assertNotNull(hiMessage);
    assertEquals("hi, baeldung", hiMessage);
 
    before = System.currentTimeMillis();
    hiMessage = greetingsService.sayHi("baeldung");
    timeElapsed = System.currentTimeMillis() - before;
  
    assertTrue(timeElapsed < 1000);
    assertNotNull(hiMessage);
    assertEquals("hi, baeldung", hiMessage);
}

Here the consumer is invoking the special service implementation, so it took more than 5 seconds for the invocation to complete the first time. When we invoke again, the sayHimethod completes almost immediately, as the result is returned from the cache.

Note that thread-local cache and JCache are also supported.

关于和zookeeper集群,负载均衡及容错参考:https://www.baeldung.com/dubbo

 

原文地址:https://www.cnblogs.com/daxiong225/p/11143599.html