Pengenalan kepada Dubbo

1. Pengenalan

Dubbo adalah RPC sumber terbuka dan rangka kerja perkhidmatan mikro dari Alibaba.

Antara lain, ia membantu meningkatkan tadbir urus perkhidmatan dan memungkinkan untuk aplikasi monolit tradisional direfleksikan dengan lancar kepada seni bina yang diedarkan dengan skala.

Dalam artikel ini, kami akan memberikan pengenalan kepada Dubbo dan ciri-ciri terpentingnya.

2. Senibina

Dubbo membezakan beberapa peranan:

  1. Penyedia - di mana perkhidmatan terdedah; pembekal akan mendaftarkan perkhidmatannya ke pendaftaran
  2. Container - tempat perkhidmatan dimulakan, dimuat dan dijalankan
  3. Pengguna - yang meminta perkhidmatan jarak jauh; pengguna akan melanggan perkhidmatan yang diperlukan dalam pendaftaran
  4. Pendaftaran - di mana perkhidmatan akan didaftarkan dan ditemui
  5. Monitor - catat statistik untuk perkhidmatan, misalnya, kekerapan pemanggilan perkhidmatan dalam selang waktu tertentu

(sumber: //dubbo.io/images/dubbo-architecture.png)

Sambungan antara penyedia, pengguna dan pendaftaran tetap berlaku, jadi setiap kali penyedia perkhidmatan dimatikan, pendaftaran dapat mengesan kegagalan dan memberi tahu pengguna.

Pendaftaran dan monitor adalah pilihan. Pengguna dapat berhubung terus dengan penyedia perkhidmatan, tetapi kestabilan keseluruhan sistem akan terjejas.

3. Ketergantungan Maven

Sebelum kita masuk, mari tambahkan kebergantungan berikut ke pom.xml kami :

 com.alibaba dubbo 2.5.7 

Versi terbaru boleh didapati di sini.

4. Bootstrapping

Sekarang mari kita mencuba ciri-ciri asas Dubbo.

Ini adalah kerangka invasif minimum, dan banyak ciri bergantung pada konfigurasi luaran atau anotasi.

Secara rasmi disarankan agar kita menggunakan fail konfigurasi XML kerana bergantung pada wadah Spring (kini Spring 4.3.10).

Kami akan menunjukkan sebahagian besar ciri menggunakan konfigurasi XML.

4.1. Pendaftaran Multicast - Penyedia Perkhidmatan

Sebagai permulaan yang cepat, kita hanya memerlukan penyedia perkhidmatan, pengguna dan pendaftaran "tidak kelihatan". Pendaftaran tidak dapat dilihat kerana kami menggunakan rangkaian multicast.

Dalam contoh berikut, penyedia hanya mengatakan "hi" kepada penggunanya:

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

Untuk membuat panggilan prosedur jarak jauh, pengguna mesti berkongsi antara muka yang sama dengan penyedia perkhidmatan, oleh itu antara muka GreetingsService mesti dikongsi dengan pengguna.

4.2. Pendaftaran Multicast - Pendaftaran Perkhidmatan

Sekarang mari kita mendaftar GreetingsService ke pendaftaran. Cara yang sangat mudah adalah menggunakan pendaftaran multicast jika kedua-dua penyedia dan pengguna berada di rangkaian tempatan yang sama:

Dengan konfigurasi kacang di atas, kami baru sahaja mengungkapkan Perkhidmatan Salam kami ke url di bawah dubbo: //127.0.0.1: 20880 dan mendaftarkan perkhidmatan tersebut ke alamat multicast yang dinyatakan dalam.

Dalam konfigurasi penyedia, kami juga menyatakan metadata aplikasi kami, antara muka untuk diterbitkan dan pelaksanaannya masing-masing oleh , dan .

The dubbo protokol merupakan salah satu daripada banyak protokol rangka kerja penyokong. Ia dibina di atas fitur Java NIO yang tidak menyekat dan ini adalah protokol lalai yang digunakan.

Kami akan membincangkannya dengan lebih terperinci kemudian dalam artikel ini.

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:

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

public class MulticastRegistryTest { @Before public void initRemote() { ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("multicast/provider-app.xml"); remoteContext.start(); } @Test public void givenProvider_whenConsumerSaysHi_thenGotResponse(){ ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("multicast/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 GreetingsService and 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:

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

4.4. Simple Registry

Note that when using an “invisible” multicast registry, the registry service is not standalone. However, it's only applicable to a restricted local network.

To explicitly set up a manageable registry, we can use a SimpleRegistryService.

After loading the following beans configuration into Spring context, a simple registry service is started:

Note that the SimpleRegistryService class is not contained in the artifact, so we copied the source code directly from the Github repository.

Then we shall adjust the registry configuration of the provider and consumer:

SimpleRegistryService can be used as a standalone registry when testing, but it is not advised to be used in production environment.

4.5. Java Configuration

Configuration via Java API, property file, and annotations are also supported. However, property file and annotations are only applicable if our architecture isn't very complex.

Let's see how our previous XML configurations for multicast registry can be translated into API configuration. First, the provider is set up as follows:

ApplicationConfig application = new ApplicationConfig(); application.setName("demo-provider"); application.setVersion("1.0"); RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("multicast://224.1.1.1:9090"); ServiceConfig service = new ServiceConfig(); service.setApplication(application); service.setRegistry(registryConfig); service.setInterface(GreetingsService.class); service.setRef(new GreetingsServiceImpl()); service.export();

Now that the service is already exposed via the multicast registry, let's consume it in a local client:

ApplicationConfig application = new ApplicationConfig(); application.setName("demo-consumer"); application.setVersion("1.0"); RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("multicast://224.1.1.1:9090"); ReferenceConfig reference = new ReferenceConfig(); reference.setApplication(application); reference.setRegistry(registryConfig); reference.setInterface(GreetingsService.class); GreetingsService greetingsService = reference.get(); String hiMessage = greetingsService.sayHi("baeldung");

Though the snippet above works like a charm as the previous XML configuration example, it is a little more trivial. For the time being, XML configuration should be the first choice if we intend to make full use of Dubbo.

5. Protocol Support

The framework supports multiple protocols, including dubbo, RMI, hessian, HTTP, web service, thrift, memcached and redis. Most of the protocols looks familiar, except for dubbo. Let's see what's new in this protocol.

The dubbo protocol keeps a persistent connection between providers and consumers. The long connection and NIO non-blocking network communication result in a fairly great performance while transmitting small-scale data packets (<100K).

There are several configurable properties, such as port, number of connections per consumer, maximum accepted connections, etc.

Dubbo also supports exposing services via different protocols all at once:

And yes, we can expose different services using different protocols, as shown in the snippet above. The underlying transporters, serialization implementations and other common properties relating to networking are configurable as well.

6. 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:

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 sayHi method completes almost immediately, as the result is returned from the cache.

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

7. Cluster Support

Dubbo helps us scale up our services freely with its ability of load balancing and several fault tolerance strategies. Here, let's assume we have Zookeeper as our registry to manage services in a cluster. Providers can register their services in Zookeeper like this:

Note that we need these additional dependencies in the POM:

 org.apache.zookeeper zookeeper 3.4.11   com.101tec zkclient 0.10 

The latest versions of zookeeper dependency and zkclient can be found here and here.

7.1. Load Balancing

Currently, the framework supports a few load-balancing strategies:

  • random
  • round-robin
  • least-active
  • consistent-hash.

In the following example, we have two service implementations as providers in a cluster. The requests are routed using the round-robin approach.

First, let's set up service providers:

@Before public void initRemote() { ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit(() -> { ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-default.xml"); remoteContext.start(); }); executorService.submit(() -> { ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml"); backupRemoteContext.start(); }); }

Now we have a standard “fast provider” that responds immediately, and a special “slow provider” who sleeps for 5 seconds on every request.

After running 6 times with the round-robin strategy, we expect the average response time to be at least 2.5 seconds:

@Test public void givenProviderCluster_whenConsumerSaysHi_thenResponseBalanced() { ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-lb.xml"); localContext.start(); GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); List elapseList = new ArrayList(6); for (int i = 0; i  e) .average(); assertTrue(avgElapse.isPresent()); assertTrue(avgElapse.getAsDouble() > 2500.0); }

Moreover, dynamic load balancing is adopted. The next example demonstrates that, with round-robin strategy, the consumer automatically chooses the new service provider as a candidate when the new provider comes online.

The “slow provider” is registered 2 seconds later after the system starts:

@Before public void initRemote() { ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit(() -> { ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-default.xml"); remoteContext.start(); }); executorService.submit(() -> { SECONDS.sleep(2); ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml"); backupRemoteContext.start(); return null; }); }

The consumer invokes the remote service once per second. After running 6 times, we expect the average response time to be greater than 1.6 seconds:

@Test public void givenProviderCluster_whenConsumerSaysHi_thenResponseBalanced() throws InterruptedException { ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-lb.xml"); localContext.start(); GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService"); List elapseList = new ArrayList(6); for (int i = 0; i  e) .average(); assertTrue(avgElapse.isPresent()); assertTrue(avgElapse.getAsDouble() > 1666.0); }

Note that the load balancer can be configured both on the consumer's side and on the provider's side. Here's an example of consumer-side configuration:

7.2. Fault Tolerance

Several fault tolerance strategies are supported in Dubbo, including:

  • fail-over
  • fail-safe
  • fail-fast
  • fail-back
  • forking.

In the case of fail-over, when one provider fails, the consumer can try with some other service providers in the cluster.

The fault tolerance strategies are configured like the following for service providers:

To demonstrate service fail-over in action, let's create a fail-over implementation of GreetingsService:

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

We can recall that our special service implementation GreetingsServiceSpecialImpl sleeps 5 seconds for each request.

When any response that takes more than 2 seconds is seen as a request failure for the consumer, we have a fail-over scenario:

After starting two providers, we can verify the fail-over behavior with the following snippet:

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

8. Summary

Dalam tutorial ini, kami mengambil sedikit gigitan Dubbo. Sebilangan besar pengguna tertarik dengan kesederhanaannya dan ciri-ciri kaya dan hebat.

Selain dari apa yang kami perkenalkan dalam artikel ini, kerangka ini memiliki sejumlah fitur yang belum dapat dijelajahi, seperti pengesahan parameter, pemberitahuan dan panggilan balik, pelaksanaan dan rujukan umum, pengelompokan dan penggabungan hasil jarak jauh, peningkatan perkhidmatan dan keserasian mundur, beberapa.

Seperti biasa, pelaksanaan sepenuhnya dapat dilihat di Github.