Hello, Dubbo is Dubbo. Take out your notebook and write it down
Evolution of software architecture
Cluster: Everyone does the same job. Share the burden
Distributed: multiple people working together to do a “big” thing
Distribution is usually accompanied by clustering
With the development of the Internet, the scale of website application is also constantly expanding, leading to the system architecture is also constantly changing.
Since the early days of the Internet, the system architecture has generally gone through the following processes: single application architecture – > vertical application architecture – > distributed architecture – >SOA architecture – > microservice architecture
1 Single application architecture
Single application architecture is to make all modules of a system into a Web project and then deploy it on a Tomcat server
-
Advantages:
- The project structure is simple, and the cost of development, testing and deployment is low
- The project is deployed on one node for easy maintenance
-
Disadvantages:
- The project modules are tightly coupled with low single point fault tolerance
- It is impossible to optimize and expand horizontally for different modules
2 Vertical application architecture
Vertical application architecture is the dismantling of an original system into multiple modules, and each module is deployed on a Tomcat server
- Advantages:
- You can optimize and scale horizontally for different modules
- Problems in one system do not affect other systems, improving the single point of fault tolerance
- Disadvantages:
- Systems are independent from each other, unable to call each other, and there will be repeated development tasks (resulting in code redundancy).
3 Distributed Architecture
Distributed architecture means that the service layer is started separately to provide services externally, and the methods in the service layer can be accessed through remote calls in the Controller
-
Advantages:
- Extract common functions into the service layer to improve code reuse
-
Disadvantages:
- Call relationships are complex and difficult to maintain
4 the SOA architecture
SOA architecture adds a scheduling center to manage the system in real time on the basis of distributed architecture.
Interview direct: Talk about the difference between clustering and distribution
-
Cluster: Multiple servers perform the same task repeatedly, that is, a task is deployed on multiple servers
-
Distributed: Multiple servers work together to complete the same task. That is, a task is divided into multiple sub-tasks and multiple sub-tasks are deployed on multiple servers to complete the same task
The summary of Dubbo
1 introduction of Dubbo
Apache Dubbo is a high-performance Java RPC framework. Its predecessor is a high-performance, lightweight open source Java RPC(Remote Procedure Call) framework developed by Alibaba, which can be seamlessly integrated with the Spring framework.
The development course
Dubbo is a distributed business framework used internally by Alibaba and opened source by Alibaba in 2012
In a very short time, Dubbo was adopted by many Internet companies and produced many derivative versions, such as netease, JINGdong, Sina, Dangdang and so on
Due to changes in Ali’s strategy, Dubbo stopped maintenance in October 2014. Subsequently, some Internet companies released their own versions of Dubbo, notably Dangdang DubboX
After a three-year hiatus, In September 2017, Alibaba announced the restart of the Dubbo project and decided to make a long-term commitment to open source in the future
Dubbo then began an intensive update that quickly integrated features and bug fixes on a large number of branches in the three years since the shutdown
In February 2012, Ali donated Dubbo to the Apache Foundation and Dubbo became an Apache Incubator project
RPC is introduced
Remote Procedure Call (RPC
It is important to note that RPC is not a specific technology, but refers to the entire network remote call process
There are many RPC frameworks in Java, such as RMI, Hessian and Dubbo
In simple terms: Machine A calls A method of machine B over the network. This process is called RPC
Core competence
Interface oriented remote method invocation
Intelligent fault tolerance and load balancing
Services are automatically registered and discovered
2. Dubbo structure
Node roles:
Call relationship description:
The service container is responsible for starting, loading, and running the service provider.
At startup, service providers register their services with the registry.
At startup, service consumers subscribe to the registry for the services they need.
The registry returns a list of service provider addresses to the consumer, and if there are changes, the registry pushes the change data to the consumer based on the long connection.
The service consumer, from the provider address list, selects one provider to call based on the soft load balancing algorithm. If the call fails, selects another one to call.
Service consumers and providers accumulate the number of calls and call time in memory, and regularly send statistics every minute
Data to the monitoring center.
Three Dubbo quick Start
1 Service registry ZK
They are introduced
Dubbo officially recommends using the ZooKeeper registry. The registry is responsible for the registration and lookup of service addresses, which is equivalent to a directory service. Service providers and consumers only interact with the registry at startup, and the registry does not forward requests, which is less stressful.
Zookeeper is a subproject of Apacahe Hadoop. It is a tree directory service that supports change push and is suitable for Dubbo service registry. It has high industrial intensity and can be used in production environment.
Zookeeper was installed and started
Unzip zookeeper-3.4.6.zip and install it immediately (without Chinese and special symbol path)
Go to the bin directory in the installation directory and double-click zkServer. CMD to start the ZooKeeper service (depending on the JDK environment).
2 Service Provider
Build modules and guide dependencies
Writing the Service Interface
public interface UserService { String sayHello(String name); }
Writing a Service implementation
@service // Use dubbo’s annotations: 1. Pass the object to ioc container 2. Public class UserServiceImpl implements UserService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
Copy the code
}
application.yml
Dubo.application. name Service name, which is the same as the module name
Dubo.registry. address The connection address of the registry
Dubbo.protocol. name Indicates the access protocol of the current service. The value can be Dubbo, RMI, Hessian, HTTP, WebService, rest, or Redis
Dubo.protocol. port Access port of the current service
Dubbo. Scan. Base – packages package scans
Dubbo: application: name: dubbo – demo – provider registry: address: zookeeper: / / 127.0.0.1:2181 protocol: name: dubbo port: 20880 scan: base-packages: com.itheima.service
Start the class
@SpringBootApplication public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class, args);
}
Copy the code
}
3 Service consumers
Build modules and guide dependencies
Duplicate service interface
public interface UserService {
String sayHello(String name);
Copy the code
}
Writing the controller
@RestController public class UserController {
@reference // dubbo private UserService UserService; @GetMapping("/sayHello") public String sayHello(String name) { return userService.sayHello(name); }Copy the code
}
application.yml
Dubo.application. name Service name, which is the same as the module name
Dubo.registry. address The connection address of the registry
Dubbo. Scan. Base – packages package scans
Dubbo: application: name: dubbo – demo – consumer registry: address: zookeeper: / / 127.0.0.1:2181 scan: base – packages: com.itheima.web
Start the class
@SpringBootApplication public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class, args);
}
Copy the code
}
4 RPC execution process
After the provider has successfully started, tell the registry my address:
5 Extract interface modules
Current code problems:
Duplicate service interface code
The service code in the two projects must be exactly the same, which is difficult to modify later
Extract a public interface module
Providers and consumers depend on this module
Maven module dependencies
Note:
- The Web layer is the consumer
- The Service and DAO belong to the provider
- Service interfaces are extracted into separate modules
- Both consumers and providers need to rely on service interface modules
- Interface modules depend on domain modules
6 knowledge summary
After using Dubbo:
Run the registry first
Run the service provider again
Finally, run the service consumer
7 Common Exceptions
1. The registry is not started
2. After the registry is started, consumers are first started
Error message: No available xxxService provider found in the registry
Solution:
- See if the provider started successfully
- See if the provider configuration file is incorrectly written (4 lines)
- Finally, let’s see if the Service annotation is useful
3. Entity classes do not implement serialization interfaces
Dubbo use details
1 the serialization
The underlying dubbo is to transfer data over the network, so the objects to be transferred must implement the serialization interface
User
@Data @NoArgsConstructor @AllArgsConstructor public class User { private Integer id; private String name; private Integer age; }
UserService
Under the Dubo-Demo-interface module
User findById(Integer id);
UserServiceImpl
In the dubo-Demo-provider module
@Override public User findById(Integer id) { return new User(id, “jack”, 18); }
UserController
Under the Dubo-Demo-consumer module
@GetMapping(“/findById”) public User findById(Integer id) { return userService.findById(id); }
2 Check during startup
Check at startup, configured on the service consumer side to proactively check the registry for corresponding service providers at startup time
If the value is set to false, the check is not performed
If set to true(the default), this represents a check that will throw an exception if the service provider is not ready
dubbo: consumer: check: false
3 Service timeout and retry
A service consumer may block and wait while invoking a service provider, causing threads to pile up and the service to go down (avalanche) if the service consumer waits forever.
To avoid this problem, Dubbo allows you to set a timeout period for the service (1s by default). If the service cannot respond after this time, it will retry twice by default (if there are other providers reconnecting to other providers). If there is no response, it will terminate the thread and throw an exception.
This time can be set on either the service caller or the service provider (if both are set, the consumer takes precedence over the provider)
Idempotent: The results of multiple operations are the same, for example, a query
Nonidempotent: inconsistent results of multiple operations such as addition or deletion
Update account set money = 100 where id = 1; This is idempotent
Update account set money = money + 100 where id = 1; This is nonidempotent
Global configuration
If set only on one side, it is recommended to set it on the provider side, and the consumer defaults to the provider value.
dubbo: provider: timeout: 3000 retries: 0 #——————————————————————- dubbo: consumer: timeout: 5000 retries: 0
Local configuration
Dubbo also supports defining timeout times on classes, which takes precedence over global configurations
@service (timeout = 3000, retries = 0) public class UserServiceImpl implements UserService{}
Public class Controller{@reference (timeout = 5000,retries = 0) private UserService UserService; }
4 Service Degradation
When a request times out and is waiting for a service response, then in high concurrency, many requests are waiting for a response because of this,
Until the outage occurs when the service resources are exhausted, and then the outage will cause other distributed services to call the outage service to run out of resources and outage.
This will lead to the breakdown of the entire distributed service.
Exception degradation: For example, an error occurred in accessing a request, but we want to have a bottom-of-the-line policy that returns a default result
Method 1:
Returns null in case of a problem
@RestController public class Controller {
@Reference(mock=”fail:return null”) UserService userService;
}
Method 2:
In the consumer of the service, defining the service degradation handling class also implements the service interface
public class UserServiceFailback implements UserService { @Override public User findById(Integer id) { User user = new User(); user.setId(-1); User.setname (” Error getting name “); return user; } / /… }
@restController@requestMapping (“user”) public class UserController {// Specify @reference (mock =) “com.itheima.service.failback.UserServiceFailback”) UserService userService;
//…. }
5 Load Balancing
In high concurrency situations, a service often needs to work as a cluster.
Then, which service provider should handle a request from the server consumer becomes a problem. At this time, it is necessary to configure the corresponding load balancing policy.
Pull out another provider
Copy the provider module and change the module name and port
@RestController public class UserController {
@Reference(loadbalance = "consistenthash")
private UserService userService;
Copy the code
}
Dubbo supports four load balancing strategies:
- Random: Select randomly by weight. This is the default value.
- Roundrobin: Round selection by weight.
- Leastactive: minimum number of active calls, random selection of the same number of active calls.
- Consistenthash: consistenthash, where requests with the same parameters are always sent to the same provider.
More than 6 version
Many times, when a new feature is introduced in a project, some users will use the new feature first, and when the user feedback is ok, all users will migrate to the new feature
Dubbo uses the Version attribute to set and invoke different versions of the same interface
The consumer specifies a version
@RestController public class UserController {
@reference (version = "v2.0") private UserService UserService;Copy the code
}
Well, this is the end of today’s article, I hope to help you confused in front of the screen