Recently on the new project need to use dubbo, so I decided to learn from the past, decided to share the use of Dubbo in a variety of environments, this post allows you to learn to use dubbo in two hours!
What is Dubbo
Dubbo is a distributed , high-performance , transparent RPC service framework , to provide service auto-registration , auto-discovery and other efficient service governance solutions , can be seamlessly integrated with the Spring Framework.Dubbo's most commonly used application is remote invocation .
There are four most core objects on the server side in Dubbo:
- ApplicationConfig: Configure current application information
- ProtocolConfig: Configure information about the protocols that provide the service
- RegistryConfig: Configure registration-related information
- ServiceConfig: Configure exposed service information
There are two core objects in the Dubbo client:
- ApplicationConfig: Configure current application information
- ReferenceConfig: Configure referenced service information
Main application scenarios for Dubbo
Transparent remote method calls, call remote methods as if they were local, with simple configuration and no API intrusion.
Soft load balancing and fault tolerance mechanism , can be used in the intranet instead of F5 and other hardware load balancer , reduce costs and reduce single point . (F5 load balancer I also came from Baidu).
Automatic service registration and discovery, no longer need to write dead service provider address, the registry based on the interface name to query the IP address of the service provider, and the ability to smoothly add or delete service providers.
Using Dubbo
The next four ways to get started with Dubbo. first of all, the native API will directly show the dubbo direct connection and registry implementation, and then the use of Spring, annotations and SpringBoot way to show how to use Dubbo respectively.
case source codeClick here
Before writing dubbo-related code, first define aPublic api servicesThe service interface is stored in this service. The service provider introduces the project, writes the implementation class, and provides the dubbo interface; the service consumer introduces the project, and calls it through the service interface of the project.
User class:
@Data //RPC calls are generally not recommended to use the lombok annotation, easy to get out of a lot of bugs, here is used for convenience
public class User implements Serializable {
private Long id; private String name; private String
private Long id; private String name; private String sex; private String
private String name; private String sex; }
}
UserService:
public interface UserService {
User getUser(Long id);
}
native API
Generate a dubbo service by means of a native API and call this dubbo service with another class:
- Introducing dependencies
There are just two core dependencies, a dubbo dependency and the public interface methods above, which need to be introduced by both the service provider and the consumer.
<dependencies>
<dependency>
<groupId></groupId>
<artifactId>dubbo</artifactId>
<version>2.7.4.1</version>
</dependency>
<dependency>
<artifactId>dubbo-api</artifactId>
<groupId></groupId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
- service provider
The service provider is configured with the following main attributes:
- application: set the name and other information of the application
- protocol :Set the protocol of the service
- register: set the connection method of the service
- service: register the services that need to be exposed
public class DubboProvider {
public static void main(String[] args) throws IOException {
//exposingUserServiceservice
//1、application
ApplicationConfig applicationConfig = new ApplicationConfig("sample-provider");
//2、protocol -dubboprotocols
ProtocolConfig protocolConfig = new ProtocolConfig();
("dubbo");
(20880);
//3、register
//direct link,不exposing到注册中心
RegistryConfig registryConfig = new RegistryConfig(RegistryConfig.NO_AVAILABLE);
//4、service
ServiceConfig serviceConfig = new ServiceConfig();
();
(new UserServiceImpl());
//5、commander-in-chief (military)application、protocol、registerRegister toservice
(registryConfig);
(protocolConfig);
(applicationConfig);
();
("service已经exposing");
();
}
}
- Serving Consumers
There are just three main steps to consumer fulfillment:
- Configure application: set the name of the application and other information
- Configure reference: mainly configure the information to be referenced
- Get the interface and call the service.
public class DubboConsumer {
public static void main(String[] args) {
//1、application
ApplicationConfig applicationConfig =new ApplicationConfig("sample-consumer");
//2、configurereference
ReferenceConfig referenceConfig = new ReferenceConfig();
(applicationConfig);
();
("dubbo://127.0.0.1:20880/?anyhost=true&application=sample&=127.0.0.1&=20880&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=&methods=getUser&pid=5936&release=2.7.4.1&side=provider×tamp=1728390413736");
UserService userService = (UserService) ();
User user = (1L);
(user);
}
}
Start the provider first, then start the consumer, if the user information is printed out it means the call was successful.
- Using zookeeper as a registry
The above Register uses a direct connection, or you can use theRegistration CenterHere we take zookeeper as an example. First of all, introduce zookeeper related dependencies in your project:
<!-- zkClient Dependencies:curator -->
<dependency>
<groupId></groupId>
<artifactId>curator-recipes</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>curator-framework</artifactId>
<version>2.13.0</version>
</dependency>
The service provider modifies one place to change the RegistryConfig to the zookeeper connection method
//register
//Direct connection without exposing to the registry center
///RegistryConfig registryConfig=new RegistryConfig(RegistryConfig.NO_AVAILABLE);
// Expose dubbo through the registry
RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");
The consumer also modifies a location by replacing the setUrl method in referenceConfig with zookeeper:
RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");
ReferenceConfig referenceConfig = new ReferenceConfig();
(registryConfig);
(applicationConfig);
();
//("dubbo://127.0.0.1:20880/?anyhost=true&application=sample&=127.0.0.1&=20880&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=&methods=getUser&pid=5936&release=2.7.4.1&side=provider×tamp=1728390413736");
Spring integration with dubbo
The way to do it through Spring is simply to take the code written in Java above and get it into a configuration file, and inject the interface into the bean container
- Introducing spring-related dependencies
Introduce additional spring dependencies under the provider and consumer modules.
<dependency>
<groupId></groupId>
<artifactId>spring-context</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>spring-core</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.37</version>
</dependency>
- Create two new configuration files in the resource folder
<?xml version="1.0" encoding="UTF-8"? >;xml version="1.0" encoding="UTF-8"?
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:dubbo="/schema/dubbo"
xsi:schemaLocation="/schema/beans
/schema/beans/ /schema/dubbo /schema/dubbo/">
<! -- Provider application information for calculating dependencies -->.
< dubbo:application name="spring-provider"/>
<! -- Expose the service address using the zookeeper broadcast registry -->
< dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<! -- Expose the service on port 20880 using the dubbo protocol -->
< dubbo:protocol name="dubbo" port="20880"/>
<! -- Declare the service interfaces to be exposed -->
<dubbo:service interface="" ref="userService" loadbalance="roundrobin"/>
<! -- implements the service just like a native bean -->
<bean class=""/>
</beans>
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:dubbo="/schema/dubbo"
xsi:schemaLocation="/schema/beans
/schema/beans/
/schema/dubbo
/schema/dubbo/">
<dubbo:application name="spring-consumer" />
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<dubbo:reference interface="" loadbalance="roundrobin"/>
</beans>
- boot class (computing)
The configuration file here and the code above all correspond to each other. The provider and consumer of the service:
SpringDubboProvider:
public class SpringDubboProvider {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("");
("The service has been exposed");
();
}
}
SpringDubboConsumer
public class SpringDubboConsumer {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("");
UserService bean = ();
((1L));
}
}
purely annotated version
The way to annotate is not to inject the bean in the xml file, the xml file just need to write the package name
- Provider Modifications
<?xml version="1.0" encoding="UTF-8"? >;xml version="1.0" encoding="UTF-8"?
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:dubbo="/schema/dubbo"
xsi:schemaLocation="/schema/beans
/schema/beans/ /schema/dubbo /schema/dubbo/">
<! -- Provider application information for calculating dependencies -->.
< dubbo:application name="anno-provider"/>
<! -- Expose service address using zookeeper broadcast registry -->
< dubbo:registry address="zookeeper://127.0.0.1:2181"/>!
<! -- Expose the service on port 20880 with the dubbo protocol -->
< dubbo:protocol name="dubbo" port="20880"/>
<! -- annotated version -->
<dubbo:annotation package="""/>
</beans>
UserService implementation class
import ;
@Service //dubbo(used form a nominal expression)@Serviceexplanatory note
public class UserServiceImpl implements UserService {
@Override
public User getUser(Long id) {
User user = new User();
(id);
("Seven");
("male");
return user;
}
}
- Consumer modifications
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:dubbo="/schema/dubbo"
xmlns:context="/schema/context"
xsi:schemaLocation="/schema/beans
/schema/beans/ /schema/dubbo /schema/dubbo/ /schema/context /schema/context/">
<dubbo:application name="anno-consumer" />
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<!-- annotated version -->
<dubbo:annotation package=""/>
<context:component-scan base-package=""/>
</beans>
controller class
@Controller
public class UserController {
@Reference //import ;
private UserService userService;
public User getUser(long id){
return (id);
}
}
SpringBoot integration dubo
Introducing core dependencies for dubbo and springboot
<!-- pull intospring-boot-starteras well asdubbocap (a poem)curatordependence -->
<dependency>
<groupId></groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.5</version>
</dependency>
<!-- Spring Bootrelevant dependencies -->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.5</version>
</dependency>
- Service providerprovider
The configurations here are written in the middle:
# Name of the current service/application
dubbo.
application.
name: springboot-provider
# Protocol and address of the registry
registry.
protocol: zookeeper
address: 127.0.0.1:2181
#Communication rules (communication protocols and interfaces)
protocol: name: dubbo
name: dubbo
port: 20880
# Load balancing algorithm
provider: dubbo
loadbalance: roundrobin
The service provider needs to write the implementation class of the service, here you need to note that the @Service annotation is used under the dubbo package:
import ;
import ;
import ;
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUser(Long id) {
User user = new User();
(id);
("Seven");
("male");
return user;
}
}
Then just add an @EnableDubbo annotation to the startup class.
@EnableDubbo
@SpringBootApplication
public class App{
public static void main(String[] args) {
(, args);
}
}
- Consumer of the service consumer
Configuration file:
# Avoid port conflict with provider, set port 8081 to access
server.
port: 8081
# Name of the current service/application
dubbo.
name: springboot-consumer
name: springboot-consumer
# Protocol and address of the registry
registry.
protocol: zookeeper
address: 127.0.0.1:2181
#Communication rules (communication protocols and interfaces)
protocol: name: dubbo
name: dubbo
port: 20880
# Load balancing algorithm
consumer: loadbalance: roundrobin
loadbalance: roundrobin
Then bring in the service object via the @Reference annotation
@SpringBootApplication
public class App{
@Reference
UserService userService;
public static void main(String[] args) {
(, args);
}
@Bean
public ApplicationRunner getBean(){
return args -> {
((1L));
};
}
}
Common Configurations for dubbo
- xml configuration
<dubbo:application/> Used to configure the current application information.
<dubbo:register/> Used to configure the connection registration related information
<dubbo:protocol/> Used to configure the protocol information for providing services, the provider specifies the protocol and the consumer passively accepts it.
<dubbo:service/> used to expose a service, a service can be exposed with multiple protocols, a service can also be registered to multiple registries. provider side configuration
<dubbo:reference/> Used to create a remote service proxy. consumer side configuration
- springboot configuration
dubbo:
application:
name: dubbo-springboot-demo-provider
protocol:
name: dubbo
port: 50052
registry:
address: zookeeper://127.0.0.1:2181
More specific configuration information can be found in:Configuration Items Reference Manual | Apache Dubbo
How to implement distributed calls with dubbo in the enterprise
In the enterprise, if the consumer calls the provider directly via RPC, theoretically the entire Jar package of the provider needs to be introduced into the project. But then other extraneous code of the service provider will also be introduced, leading to code pollution.
Therefore the actual development of theAn additional layer of API modules is added between the service provider and the callerThis API is for the definition of the interface of the Service and the request instance of the interface. This API mainly writes the interface definition of the Service, the return instance object of the interface and the request instance object of the interface. In a nutshell.All definitions are done in the API。
When you use it, the service provider introduces this API and then writes the implementation method, and the service consumer introduces this API and then calls it directly via dubbo.
In addition to enterprise development, there may be multiple interface implementations, in which case you can set group, version, etc. for Service to differentiate.
About the Author.
From the first-line programmer Seven's exploration and practice, continuous learning iteration in the~
This article is included in my personal blog:https://
Public number: seven97, welcome to follow~