In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use SpringCloudAlibaba to integrate Dubbo, the article is very detailed, has a certain reference value, interested friends must read it!
SpringCloudAlibaba integrates Dubbo
Spring Cloud is a relatively complete architectural scheme, while Dubbo is only a service governance and RPC implementation scheme.
The registry of Dubbo uses ZooKeeper, while the registry of Spring Cloud does not support ZooKeeper. It was not until the emergence of Spring Cloud Alibaba that the Nacos in Spring Cloud Alibaba was used as a service registry, under which Ribbon or Feign could be used as a traditional Spring Cloud application to achieve service consumption, and an additional RPC scheme supported under Spring Cloud Alibaba: Dubbo was provided.
Build the service interface public interface HelloService {String hello (String name);} build the service interface provider
(1) create a Spring Boot project and introduce the API package built in the first step in pom.xml and Spring Cloud Alibaba's dependency on Nacos and Dubbo
Top.onething product-api 1.0-SNAPSHOT com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config 2.2.1.RELEASE org.springframework.boot spring-boot-starter-web 2.2.5.RELEASE com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery 2.2.1.RELEASE com.alibaba.cloud spring-cloud-starter-dubbo 2.2.1.RELEASE org.apache.httpcomponents httpclient 4.5.4 compile
Spring-cloud-starter-dubbo is based on spring-cloud-starter-commons, and the org.apache.http.client.HttpClient class does exist in the old version of httpclient, but it does not exist in the new version using the internal org.apache.http.impl.client.HttpClientBuilder class. If there is no HttpClient on the classpath, HttpClientConfiguration automatic configuration will fail the automatic configuration of HttpClientConfiguration fails due to the old dependency on HttpClient. The exception is as follows:
Java.lang.IllegalStateException: Error processing condition on org.springframework.cloud.commons.httpclient.HttpClientConfiguration$ApacheHttpClientConfiguration.apacheHttpClientBuilder
Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.client.HttpClientBuilder
(2) implement Dubbo interface
@ Servicepublic class HelloServiceImpl implements HelloService {@ Override public String hello (String name) {return "hello" + name;}}
Note: the @ Service annotation is not for Spring, but for dubbo, with the fully qualified name: org.apache.dubbo.config.annotation.Service
(3) configure information related to Dubbo service
The configuration instructions are as follows:
Spring: application: name: dubbo-consumer cloud: nacos: discovery: server-addr: www.onething.top:8848 # address of nacos Service Registry cluster-name: consumer-cluster # Cluster name namespace: b7ef9579-df75-41c2-8a95-e04aa03c273a # Namespace config: server-addr: www.onething.top:8848 # nacos configuration Center address Namespace: b7ef9579-df75-41c2-8a95-e04aa03c273a file-extension: yaml # configuration file suffix refresh-enabled: true # default true: automatically refresh dubbo: protocol: # protocol configuration exposed by the Dubbo service Where the sub-attribute name is the protocol name, and port is the protocol port (- 1 means self-increment port, starting from 20880) name: dubbo port:-1 # dubbo protocol default port is 20880, RMI protocol default port is 1099 http and hessian protocol default port is 80 If port is not configured, the default port is automatically adopted, and if configured to-1, an unoccupied port is assigned. Dubbo 2.4.0. The assigned port grows on the basis of the default port of the protocol. Make sure that the port segment is controllable. Registry: # dubbo service registration port, registry server address. If the address has no port, the default is 9090, and multiple addresses in the same cluster are separated by commas. For example: ip:port,ip:port # where the prefix spring-cloud description: Mount to the Spring Cloud registry address: spring-cloud://www.onething.top:8848 # check: false # disable the relevant check of whether the registry is started. False means that if you do not check whether the registry is started, there will be no error cloud: subscribed-services: dubbo-product consumer: check: false # check whether the subscription service is started [when checking No service provider will report an error]
Dubbo.scan.base-packages: specifies the scanning benchmark package for the Dubbo service implementation class
Dubbo.protocol: the protocol configuration exposed by the Dubbo service, where the subattribute name is the protocol name and port is the protocol port (- 1 means self-increment port, starting from 20880)
Dubbo.registry: Dubbo service registry configuration, where the value of the child attribute address is "spring-cloud://localhost", indicating that it is mounted to the Spring Cloud registry
Note: if you use Spring Boot 2.1and later, you need to add the configuration spring.main.allow-bean-definition-overriding=true
(4) create the application main class
@ EnableDiscoveryClient [this comment can be omitted] @ SpringBootApplicationpublic class DubboServerApplication {public static void main (String [] args) {SpringApplication.run (DubboServerApplication.class, args);}} build service interface consumption method
(1) create a Spring Boot project and introduce the API package built in the first step and Spring Cloud Alibaba's dependence on Nacos and Dubbo into pom.xml, which is consistent with the service provider.
Top.onething product-api 1.0-SNAPSHOT com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config 2.2.1.RELEASE org.springframework.boot spring-boot-starter-web 2.2.5.RELEASE com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery 2.2.1. RELEASE com.alibaba.cloud spring-cloud-starter-dubbo 2.2.1.RELEASE
(2) configure information related to Dubbo service
Spring: application: name: dubbo-consumer cloud: nacos: discovery: server-addr: www.onething.top:8848 # address of nacos Service Registry cluster-name: consumer-cluster # Cluster name namespace: b7ef9579-df75-41c2-8a95-e04aa03c273a # Namespace config: server-addr: www.onething.top:8848 # nacos configuration Center address Namespace: b7ef9579-df75-41c2-8a95-e04aa03c273a group: test-group file-extension: yaml # configuration file suffix dubbo: protocol: # Dubbo service exposed protocol configuration Where the sub-attribute name is the protocol name, and port is the protocol port (- 1 means self-increment port, starting from 20880) name: dubbo port:-1 # dubbo protocol default port is 20880, RMI protocol default port is 1099 http and hessian protocol default port is 80 If port is not configured, the default port is automatically adopted, and if configured to-1, an unoccupied port is assigned. Dubbo 2.4.0. The assigned port grows on the basis of the default port of the protocol. Make sure that the port segment is controllable registry: # where the prefix spring-cloud description: mount to the Spring Cloud registry address: spring-cloud://www.onething.top:8848 # dubbo service registration port, registry server address. If the address has no port default is 9090, and multiple addresses in the same cluster are separated by commas. Such as: ip:port,ip:port cloud: subscribed-services: dubbo-product
(3) create the application main class and implement an interface in which the Dubbo service is called
EnableDiscoveryClient@SpringBootApplication@RestControllerpublic class DubboClientApplication {@ Reference HelloService helloService; public static void main (String [] args) {SpringApplication.run (DubboClientApplication.class, args);} @ GetMapping ("/ test") public String test () {return helloService.hello ("didispace.com");}}
Note: the @ Reference annotation here is org.apache.dubbo.config.annotation.Reference
Dubbo summary of SpringCloudAlibaba
GitHub address: https://github.com/apache/dubbo
The story of Dubbo is quite long, and there are examples of calls in Demo, so I won't supplement the examples. There are also some examples on my gitee repository that I can refer to. At present, I will only make a summary for the latest version 2.7.7.
In addition, with regard to Dubbo, after so many years, many people pay more attention to some issues such as the dynamic proxy of Dubbo, the underlying Netty protocol and so on. But I think we should pay more attention to what Dubbo does and what comes to mind in the service invocation scenario, which should be more valuable than handwritten Dubbo. The relationship between architects and programmers is like the gap between architects and programmers. It is not that architects write better code than programmers, but that architects can consider a variety of situations and combine them into systematic solutions to practical problems.
Overview of Dubbo
Description of the official website:
High-performance RPC invocation oriented to interface proxy: provides high-performance proxy-based remote invocation capability. The service takes the interface as the granularity, shielding the underlying details of remote invocation for developers.
Intelligent load balancing: built-in a variety of load balancing strategies, intelligently perceive the health status of downstream nodes, significantly reduce call latency and improve system throughput.
Automatic registration and discovery of services: support a variety of registry services, real-time awareness of service instances online and offline.
Highly scalable: following the design principles of microkernel + plug-ins, all core competencies such as Protocol,Transport,Serialization are designed as extension points and treat built-in and third-party implementations equally.
Runtime traffic scheduling: built-in conditions, scripts and other routing strategies, by configuring different routing rules, it is easy to achieve grayscale release, priority in the same computer room and other functions.
Visual service governance and operation and maintenance: provide rich service governance and OPS tools, query service metadata at any time, call statistics for service health status, issue routing policies in real time, and adjust configuration parameters.
In this figure, you can see the responsibilities of each role of Dubbo. Registery is responsible for service discovery and registration, Provider registers service information with Registry, Consumer subscribes to service information on Registry, and Registry will push it to Consumer in time. Consumer then selects a Provider from the list of services to make the service call.
Dubbo configuration mode
There are three ways to configure Dubbo services: API mode, Spring-based XML mode and SpringBoot-based Properties mode. All three ways of service configuration are implemented in the Demo project, so I won't say much about it. What you want to record here is the priority of the various configurations.
The relationship between the three configuration modes
Obviously, API is no longer a service-oriented configuration, but a low-level implementation, showing how to assemble several core objects of Dubbo into services. Under normal circumstances, it is not very useful, but it can be forcibly used occasionally in some environments that are separated from Spring, such as MapReduce, spark computing and so on.
In fact, the effects of the latter two configurations are equivalent. For example, dubbo.application.name=foo and are equivalent, while dubbo.registry.address=nacos://localhost:8848 and {xml} > {properties}. Also, if there are multiple dubbo.properties in a project (for example, there are configuration files in multiple jar packages), dubbo will randomly read a configuration file and throw exception information. The official recommendation is also to use xml for configuration.
In addition, there is another annotation-based service declaration method for SpringCloud-based properties configuration: @ Service exposes the service and @ Reference invokes the service, which is actually equivalent to the way xml is configured.
Configuration priority of server side and consumer side
There are many service attributes, such as retris (number of retries), timeout (timeout), loadbalance (load method), and so on, which can be configured on both the service provider side and the service consumer side. At this point, the configuration of the service consumer side takes precedence over the service provider side. The configuration of the service provider is equivalent to the default properties of the service, so it is officially recommended to configure as many of these service attributes as possible on the service provider. In addition, officials also recommend that more detailed service configuration be provided on the server side, for example, when configuring services, and for each method if possible. For example:
This specifies the thread pool 200, while the thread pool for findAllPerson is 50. 0.
Specify the Cache File of the dubbo
It is officially recommended that file be specified in the registry. For example. This Cache File can cache the service registration information so that the consumer can still make service invocation after the registry stops the service. Because this file is very important, although it is not specified, it will be generated locally by default, but the official recommendation is to specify the cache file separately, and be careful not to have multiple projects specify the same cache file. This will cause competition for file write permissions and overwrite service registration information.
This CacheFile mechanism allows consumers to bypass the registry to access the service provider, and if you need to prevent this, you can use dubbo's token verification mechanism, which requires permission verification in the registry before access. The enabling method is also very simple. You can specify the token attribute in provider or service:
Some other interesting places
Many of the features of dubbo are described in detail in the official documentation, and here are some interesting features. Others can refer to the official documents.
Fault-tolerant mechanism of service cluster
You can specify a cluster fault tolerance mechanism in service, such as
The default is Failover, which automatically finds another provider and initiates a retry when an access error occurs (timeout, etc.). You can specify the number of retries by specifying retries-the number of times the retries configuration does not include the first request. This is usually used for read operations, but for write operations, it is easy to cause service idempotent problems.
Failfast: make only one service call, and report an error immediately if something goes wrong. This comparison is suitable for write operations.
Failsafe: if there is an error or exception in the service invocation, ignore it directly. This comparison applies to operations such as logging that allow failures.
Failback: automatic fault recovery. Failed requests are recorded in the background and retransmitted regularly. This comparison is suitable for message-driven scenarios.
Forking: requests are made to multiple servers at the same time. Once one service provider returns success, the service invocation is successful. This comparison is suitable for read operations with high real-time requirements. But obviously, this will waste more service resources. You can configure the number of parallelism using the fork property.
BroadCast: simultaneously initiates requests to all service providers, requests in turn, and reports each error. This is typically used to notify all servers for operations such as cache updates.
Local service stub and local masquerade local stub, local mock
1. In general, the service consumer has only one interface, and the implementation of the service invocation depends on the service provider. However, sometimes, the service provider wants to do some local operations on the service consumer, such as doing ThreadLocal caching, parameter checking, returning Mock fake data when the call fails, and so on. In this way, some things that need to be done with Hystrix on the consumer side in SpringCloud can be processed directly for the consumer side with this local service stub on the server side, which allows the consumer side to further ignore the details of service invocation. For example, do the following configuration on the service provider:
Or
The service provider can then provide a local stub method so that the sayHello method of the BarServiceStub executes locally on the consumer side, allowing the consumer side to return fault-tolerant data after the service call fails.
The public class BarServiceStub implements BarService {private final BarService barService; / / constructor passes in the real remote proxy object public BarServiceStub (BarService barService) {this.barService = barService;} public String sayHello (String name) {/ / this code is executed on the client side, you can do ThreadLocal local cache on the client side, or pre-verify whether the parameter is valid, and so on try {return barService.sayHello (name) } catch (Exception e) {/ / you can be fault tolerant, you can do any AOP interception return "fault tolerant data";}
2. For fault-tolerant scenarios like Mock, dubbo can be configured more simply by using the mock attribute.
Or
In this way, in barServiceMock, instead of using try cache, you only need to focus on post-cache processing.
Public class BarServiceMock implements BarService {public String sayHello (String name) {/ / you can forge fault-tolerant data, and this method is executed by return "fault-tolerant data" only when RpcException occurs;}}
In this way, service consumers can save a lot of unnecessary try cache operations.
3. In the mock property, you can return some specified objects directly, so that even the implementation code can be omitted. For example:
Objects that can be returned by the mock property are:
Empty: empty object, which represents the default value of the basic type, or an empty collection, etc.
Null: null object in java
Boolean: true or false
JSON format: an object's JSON deserializes the object.
Also, in the mock property, you can simply throw an exception
/ / throw a RPCException exception / / throw a specified exception
4. In this version of dubbo, the mock attribute also supports the mock behavior of force and fail.
Fail is consistent with the default process, which means that it only occurs when an exception occurs in the remote call on the consumer side.
Force means not to make a remote call, but to return mock data directly. This is still useful in debugging.
Both force and fail support combining with return or throw above. 、
Or
5. This local mock is quite powerful when dealing with service invocation exceptions. It is officially recommended that you try to use mock at the method level rather than on the entire service. Like this, use mock. Exe only on the sayHello method.
6. Note that stub and mock can be specified on both the provider side and the consumer side of the service, and the priority of the consumer side is higher than that of the provider side.
Generalization Service GenericService
Dubbo services are always interface-oriented, which means that service invocations always require a fixed interface object, which is secure, but not flexible enough. On the other hand, Dubbo can increase service flexibility through GenericService Pan-China service.
1. Service provider:
On the service provider side, you can replace all interface implementations with org.apache.dubbo.rpc.service.GenericService. For example, first provide a service as follows:
For the specified MyGenericService, you can implement the extension logic by inheriting GenericService:
Public class MyGenericService implements GenericService {@ Override public Object $invoke (String methodName, String [] parameterTypes, Object [] args) throws GenericException {if ("sayHello" .equals (methodName)) {return "Welcome" + args [0];}
This allows you to respond to service requests such as barService.sayHello (String args) on the server side without the need for an interface.
This generalized service approach also supports service exposure in API mode, which is basically equivalent to the configuration of xml.
2. Generalize service invocation
To generalize the service invocation, you only need to specify generic as true in reference.
The generalization service has no predefined methods, and needs to be called using the $invoke method of GenericService
GenericService barService = (GenericService) applicationContext.getBean ("barService"); Object result = barService.$invoke ("sayHello", new String [] {"java.lang.String"}, new Object [] {"World"})
This invocation method also supports service invocation in API format.
The return object of the generalization method, if it is a POJO object, returns the information of POJO as a Map structure, similar to the following structure
Map map = new HashMap (); / / Note: if the parameter type is an interface, or if the parameter type is missing generics such as List, you can specify the type through the class attribute. Map.put ("class", "com.xxx.PersonImpl"); map.put ("name", "xxx"); / / attribute map.put of Person ("password", "yyy")
Service management console
If Dubbo uses Nacos as its registry, Nacos can already act as a service console.
There is another project that can replace the original Dubbo Admin as the service management console of Dubbo. Github address: https://github.com/apache/dubbo-admin an administrative console based on the separation of front and rear ends of Vue.js and Verify+SpringBoot.
The Chinese official website looks comfortable, rich in examples, and the explanation is also very simple and exhaustive. The current version of Dubbo still has some functions such as distributed transactions that have not yet been implemented. It is expected that Dubbo will be more powerful.
The above is all the content of the article "how to integrate Dubbo with SpringCloudAlibaba". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 233
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.