当前位置:网站首页>Custom RPC project - frequently asked questions and explanations (Registration Center)
Custom RPC project - frequently asked questions and explanations (Registration Center)
2022-07-06 13:36:00 【Li bohuan】
Take the book back , Customize RPC project —— Common problems and detailed explanations (Netty piece )_ Li bohuan's blog -CSDN Blog , Let's talk about it later , This RPC Frequently asked questions about the project :
Project address :https://blog.csdn.net/qq_40856284/category_10138756.html
Four 、 Registry Center
1. Why use a registry ?
Before using and learning the registry , First of all, we need to be clear , Why use a registry ? With the development of Internet architecture ( Single application architecture ==> Vertical application architecture ==> Distributed architecture ==>SOA framework ==> Microservice architecture ), More and more services , The dependencies between services are also more complex , It is difficult to directly call services , The implementation process is also more complex , And to improve the reliability of the service , The registration center came into being .
The concept of registry plays an important role in the architecture of service-oriented design , Whether in SOA Architecture is still in the microservice architecture , The role of the registry can be summed up in a word Storage and scheduling services , Implement services and registries , Services and communication between services . The registry can be said to be in the microservice architecture ” Mail list “, It records the mapping relationship between service and service address . In a distributed architecture , The service will register here , When a service needs to call another service , Just find the address of the service here , To call . Here are some common registry features :
2. Why use Nacos As the registration center of the project ?
Nacos Alibaba is an open-source dynamic service discovery that is easier to build cloud native applications 、 Configuration management and service management platform .( Configuration center 、 Registry Center )
Look at the watch above ,nacos The most comprehensive features supported . Open the box , Simple to use , I haven't found a big hole yet ,nacos More features , The community is more active . If you are interviewing Ali , Direct said Because it was developed by Ali , Stand the test of various applications in large factories , There must be no problem .
3. Common registry differences ?
See this article . Microservices : Registry Center ZooKeeper、Eureka、Consul 、Nacos contrast _ Qiyan's blog -CSDN Blog _consul nacos
4. What are the minimum conditions for a registration center ?
Service registration interface : The service provider completes the service registration by calling the service registration interface .
Service de registration interface : The service provider calls the service deregistration interface to complete the service deregistration .
Heartbeat reporting interface : The service provider completes the node survival status reporting by calling the heartbeat reporting interface .
Service subscription interface : The service consumer completes the service subscription by calling the service subscription interface , Get the list of available service provider nodes .
Service change query interface : The service consumer changes the query interface by calling the service , Get the latest list of available service nodes .
Service query interface : Query the service information currently registered in the registry .
Service modification interface : Modify the information of a service in the registry .
5. The registration center is a single machine or a cluster , What if one of them hangs up ? Uniformity , How to guarantee reliability ?
In my project , It is a stand-alone version nacos.nacos You can see the following blog for the cluster deployment scheme of
Then we need to realize the registration center from stand-alone version to distributed cluster , There are several key problems to be solved :
The relationship between cluster members and member discovery problems
Data replication and consistency among cluster members
Data replication mechanism and data partition strategy
Specific solutions can be seen : Design principle and implementation of distributed cluster in microservice registry Golang Realization (136.la)
6. What do distributed data consistency protocols know ?
7.CAP Theoretical understanding ?
CAP Theory is the most important theory in distributed architecture
- C Uniformity : For each read operation of the client , Or read the latest data , Either the read failed . let me put it another way , Consistency is from the perspective of distributed system , A commitment to clients accessing the system : Or I'll return you an error , Or I'll return you the absolutely consistent latest data , It's not hard to see. , It emphasizes that the data is correct .
- A Usability : Any client request can get response data , There are no response errors . let me put it another way , Availability is from the perspective of distributed systems , Another commitment to customers accessing the system : I will definitely return the data to you , It won't return you an error , But the data is not guaranteed to be up-to-date , The emphasis is not to make mistakes .
- P Zone tolerance : Because the distributed system communicates through the network , The network is unreliable . When any number of messages are lost or arrive late , The system will continue to provide services , Will not hang up . let me put it another way , Partition tolerance is from the perspective of distributed system , Another commitment to the client accessing the system : I'll keep running , No matter what kind of data synchronization problem occurs inside me , The emphasis is not to hang up .
All distributed systems must have partition tolerance , Because partition tolerance is the basic condition of distributed systems , But there can only be one consistency and availability , It's just CP perhaps AP The system of , There is no such thing as CAP All established systems . Because in order to meet the consistency, the system must copy the data to each micro service , This leads to a great performance consumption , There will be usability problems , So you can't have both .
8. Any request ( Traffic ) Will you call the registration center when you come here ?
First meeting , When Ask the registry after , Save the service list locally ( Consumer memory ), Convenient for future use .
9. If it's how you design one nacos ,rpc How to call .
【Nacos】Nacos Principle analysis _Coinker The blog of -CSDN Blog _nacos Principle
10.raft Understand ?
Nacos Of Raft Algorithm _ Overtime crazy blog -CSDN Blog _nacos raft
11. In the project nacos Specific use of the registry
Introduce dependencies
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.3.0</version>
</dependency>
First, define an interface ,ServiceRegistry As a remote registry (Nacos) Use
public interface ServiceRegistry {
/**
* Register a service into the registry
*
* @param serviceName The service name
* @param inetSocketAddress The address where the service is provided
*/
void register(String serviceName, InetSocketAddress inetSocketAddress);
}
register The method is to put the name of the service ( The interface name ) And address are registered in the service registration center , The interface has , We can write implementation classes , We achieve one Nacos As the implementation class of the registry :NacosServiceRegistry, We can also use ZooKeeper As a registry , Just implement the interface .
public class NacosServiceRegistry implements ServiceRegistry {
private static final Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);
@Override
public void register(String serviceName, InetSocketAddress inetSocketAddress) {
try {
NacosUtil.registerService(serviceName, inetSocketAddress);
} catch (NacosException e) {
logger.error(" An error occurred while registering the service :", e);
throw new RpcException(RpcError.REGISTER_SERVICE_FAILED);
}
}
}
Here is a Nacos The utility class registerService Method to register the service ,NacosUtil Class is defined as follows , Three methods are mainly implemented , Registration service , Get all instances of the service and log out of the service .
public class NacosUtil {
private static final Logger logger = LoggerFactory.getLogger(NacosUtil.class);
private static final NamingService namingService;
private static final Set<String> serviceNames = new HashSet<>();
private static InetSocketAddress address;
private static final String SERVER_ADDR = "127.0.0.1:8848";
static {
namingService = getNacosNamingService();
}
public static NamingService getNacosNamingService() {
try {
return NamingFactory.createNamingService(SERVER_ADDR);
} catch (NacosException e) {
logger.error(" Connect to Nacos Errors occur from time to time : ", e);
throw new RpcException(RpcError.FAILED_TO_CONNECT_TO_SERVICE_REGISTRY);
}
}
public static void registerService(String serviceName, InetSocketAddress address) throws NacosException {
namingService.registerInstance(serviceName, address.getHostName(), address.getPort());
NacosUtil.address = address;
serviceNames.add(serviceName);
}
public static List<Instance> getAllInstance(String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
public static void clearRegistry() {
if(!serviceNames.isEmpty() && address != null) {
String host = address.getHostName();
int port = address.getPort();
Iterator<String> iterator = serviceNames.iterator();
while(iterator.hasNext()) {
String serviceName = iterator.next();
try {
namingService.deregisterInstance(serviceName, host, port);
} catch (NacosException e) {
logger.error(" Log out of service {} Failure ", serviceName, e);
}
}
}
}
}
Nacos It's easy to use , adopt NamingFactory establish NamingService Connect Nacos, The connection process is written in a static code block , Automatically connect when the class is loaded .namingService It provides two very convenient interfaces ,registerInstance and getAllInstances Method , The former can be directed to Nacos Registration service , The latter can get a list of all providers that provide a service . So the two methods of the interface only need to be wrapped .
stay NacosUtil In which we pass getAllInstance After getting the list of all providers of a service , You have to choose one , This involves the load balancing strategy , Here we choose the first 0 individual , Later, we will explain load balancing in detail .
Next , We modify RpcServer Interface , Add a new method publishService, Used to direct to Nacos Registration service :
<T> void publishService(Object service, Class<T> serviceClass);
Then you just need to implement this method , With NettyServer For example ,NettyServer You need to create a ServiceRegistry 了 :
public NettyServer(String host, int port) {
this.host = host;
this.port = port;
serviceRegistry = new NacosServiceRegistry();
serviceProvider = new ServiceProviderImpl();
}
public <T> void publishService(Object service, Class<T> serviceClass) {
if(serializer == null) {
logger.error(" Serializer not set ");
throw new RpcException(RpcError.SERIALIZER_NOT_FOUND);
}
serviceProvider.addServiceProvider(service);
serviceRegistry.register(serviceClass.getCanonicalName(), new InetSocketAddress(host, port));
}
there serviceProvider Is the instance object of the local saved service class ,publishService The service needs to be saved in the local registry , Also register to Nacos On .
Finally, there is the service discovery part , Let's summarize it later with load balancing ! I think it's useful for everyone , You can give bloggers a compliment ~
边栏推荐
- Change vs theme and set background picture
- Design a key value cache to save the results of the most recent Web server queries
- 3.猜数字游戏
- Tyut outline of 2022 database examination of Taiyuan University of Technology
- View UI Plus 发布 1.1.0 版本,支持 SSR、支持 Nuxt、增加 TS 声明文件
- Voir ui plus version 1.3.1 pour améliorer l'expérience Typescript
- 受检异常和非受检异常的区别和理解
- Inheritance and polymorphism (Part 2)
- Atomic and nonatomic
- MySQL中count(*)的实现方式
猜你喜欢
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
6. Function recursion
arduino+水位传感器+led显示+蜂鸣器报警
Questions and answers of "signal and system" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
The latest tank battle 2022 - Notes on the whole development -2
这次,彻底搞清楚MySQL索引
Relational algebra of tyut Taiyuan University of technology 2022 database
MySQL Database Constraints
Common method signatures and meanings of Iterable, collection and list
Introduction and use of redis
随机推荐
最新坦克大战2022-全程开发笔记-2
Differences and application scenarios between MySQL index clock B-tree, b+tree and hash indexes
[the Nine Yang Manual] 2019 Fudan University Applied Statistics real problem + analysis
View UI plus released version 1.3.0, adding space and $imagepreview components
Smart classroom solution and mobile teaching concept description
Arduino+ water level sensor +led display + buzzer alarm
Implement queue with stack
Data manipulation language (DML)
7.数组、指针和数组的关系
Common method signatures and meanings of Iterable, collection and list
View UI Plus 发布 1.2.0 版本,新增 Image、Skeleton、Typography组件
【手撕代码】单例模式及生产者/消费者模式
Wei Pai: the product is applauded, but why is the sales volume still frustrated
【话题终结者】
凡人修仙学指针-1
MPLS experiment
优先队列PriorityQueue (大根堆/小根堆/TopK问题)
【九阳神功】2018复旦大学应用统计真题+解析
仿牛客技术博客项目常见问题及解答(二)
[Topic terminator]