当前位置:网站首页>I Build a simple microservice project
I Build a simple microservice project
2022-07-04 04:05:00 【Years are exquisite】
One . Build a simple microservice project
1. Evolution from monomer architecture to microservice architecture
The monomer architecture we first came into contact with , The whole system has only one project , Packing is often done war package , Then deploy To a single tomcat above , This is the monomer architecture , Pictured :
Advantages of single architecture
1、 Simple structure , Simple deployment
2、 Less hardware resources are required
3、 Cost savings
shortcoming
1、 Version iteration is slow , Often changing a code will affect the overall situation
2、 Cannot satisfy certain concurrent access
3、 Code maintenance is difficult , All the code is in one project , There is a risk of being modified by others
With the expansion of business , Development of the company , Monomer architecture can't meet our needs slowly , We need to change the architecture change , The simplest way we can think of is to add machines , Scale out applications . Pictured :
This architecture seems to solve our problem temporarily , But after the number of users slowly increases , We can only solve it by adding machines horizontally , There will still be slow version iteration , Code maintenance difficulties . And user requests are often read more and write less , Therefore, it is only the modules with large business volume that may really need to be expanded , Now the whole project has been expanded , This is virtually a waste of resources , Because other modules may not need to be expanded at all to meet the needs . So we need to treat the whole work The process is split according to the module , The split architecture is shown below :
After the module is split , Modules need to communicate with each other through interface calls , Load balancing is carried out between modules through shunting software . This architecture solves the previous problems of resource waste and code management , Because we split the system , Each module has its own project , For example, I modify the commodity module , There is no need to worry about whether it will affect the shopping cart module . But this kind of architecture extension is very troublesome , Once the machine needs to be added horizontally , Or the machine needs to be modified nginx To configure , Once there are more machines ,nginx The amount of configuration is an unfinished job .OK, Now SOA clothing Business governance framework came into being , The architecture is as follows :
Based on the SOA frame , Expansion is very convenient , Because there is no need to maintain the shunting tool , But we should start When you use it, you will pass the service http To register with the registry .
stay SOA There are generally three roles in the framework :1、 Registry Center 2、 service provider 3、 Service consumer
1、 Registry Center
Maintain a list of services in the registry
2、 service provider
When the service provider starts, it will register itself in the registry
3、 Service consumer
When the service consumer starts , Get the list of services in the registry , Then, when calling, select a service from the list to call .
Characteristics of microservice Engineering :
1、 Expand flexibility
2、 Each application is small
3、 The service boundary is clear , Attend to each one's own duties
4、 More packaged applications , It is often necessary to resort to CI Continuous integration tools
2. Simple microservice engineering construction
1、 Registration center construction (eureka Server side : netflix-eureka-server)
Springcloud in , We choose eureka As a registry ,springcloud The project is based on springboot engineering . pom.xml in jar Packet dependency :
<!--parent-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--Springcloud Version of -->
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
</properties>
<!--Eureka Server initiator import -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--Springcloud Dependent warehouse import -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
application.properties The configuration file ( Can't call bootstrap.properties)
server.port=8763
eureka.instance.hostname=localhost
# Whether to register to eureka
eureka.client.registerWithEureka=false
# Whether from eureka Pull the registration information from
eureka.client.fetchRegistry=false
## expose eureka Address of service
# http://localhost:8763/eureka/
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
# Self-protection model , When the network partition appears 、eureka When too many clients are lost in a short period of time , Will enter self-protection mode , That is, a service does not send a heartbeat for a long time ,eureka It will not be deleted , The default is true
eureka.server.enable-self-preservation=true
#eureka server Time interval to clean up invalid nodes , Default 60000 millisecond , namely 60 second
eureka.server.eviction-interval-timer-in-ms=60000
# Service offline manually delete request http://localhost:8763/eureka/apps/MICRO-ORDER/localhost:xxx:8084
Start class
package len.hgy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public interface EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
see
http://localhost:8763/
2、 service provider (eureka client : netflix-eureka-client)
Pom Of jar Packet dependency , Everything else eureka The server side is the same , Only the service provider should register the service to eureka Server side , So the service provider is eureka The client of , So you need to import eureka Initiators for clients .
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
bootstrap.properties
spring.application.name=micro-order
server.port=8084
eureka.client.serviceUrl.defaultZone=http://localhost:8763/eureka/
# There is a default configuration
# Renewal of service , The interval between heartbeats
eureka.instance.lease-renewal-interval-in-seconds=30
# If the heartbeat time was sent before ,90 Seconds did not receive a new heartbeat , Talk about culling Services
eureka.instance.lease-expiration-duration-in-seconds=90
# Express eureka client How often do I get the service registration information , The default is 30 second
eureka.client.registry-fetch-interval-seconds=30
Start class
package len.hgy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication(scanBasePackages = {
"len.hgy"})
// Sign up to eureka
@EnableEurekaClient
@MapperScan("len.hgy.dao")
public class MicroOrderApplication {
public static void main(String[] args) {
SpringApplication.run(MicroOrderApplication.class, args);
}
}
3、 Service consumer (eureka client : netflix-eureka-client)
pom It is basically similar to the property configuration file , The consumer is responsible for invoking the service provider , So you need to call the client
rely on
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
bootstrap.properties
# Whether to register to eureka
eureka.client.registerWithEureka=true
# Whether from eureka Pull the registration information from
eureka.client.fetchRegistry=true
eureka.client.serviceUrl.defaultZone=http://localhost:8763/eureka/
Start class
package len.hgy;
import len.hgy.service.feign.StudentService;
import len.hgy.service.feign.TeacherServiceFeign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication(scanBasePackages = {
"len.hgy"})
// Sign up to eureka
@EnableEurekaClient
// Open the circuit breaker function
//@EnableCircuitBreaker
// Turn on feign Support ,clients Specify which class to turn on feign
//@EnableFeignClients(clients = {StudentService.class,TeacherServiceFeign.class})
public class MicroWebApplication {
@Bean
// Load balancing annotation
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate(); // Use this bean Only instances can be load balanced
}
public static void main(String[] args) {
SpringApplication.run(MicroWebApplication.class,args);
}
}
When calling a service, it is called according to the service name of the service provider
public static String SERVIER_NAME = "micro-order";
@Override
public List<ConsultContent> queryContents() {
s.incrementAndGet();
List<ConsultContent> results = restTemplate.getForObject("http://" + SERVIER_NAME + "/user/queryContent", List.class);
return results;
}
Name of service provider , Add the interface name of the service provider to complete the call . When service providers and service consumers start, they will register services in the service registry ,eureka The server can also use The service registration status can be viewed in the interface :
http://localhost:8763/
call web Take a look at the interface test
// controller
package len.hgy.controller;
import len.hgy.bean.ConsultContent;
import len.hgy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryUser")
public List<ConsultContent> queryUser() {
return userService.queryContents();
}
@RequestMapping("/queryMonitor")
public String queryMonitor() {
return userService.queryMonitor();
}
}
http://localhost:8083/user/queryUser
3. Eureka User authentication
Connect to eureka You need to bring the user name and password of the connection
Eureka Server transformation
add to security starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> // spring-boot
</dependency>
close csrf verification
package hgy.security;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// close csrf
http.csrf().disable();
// Open authentication :URL Format login must be httpBasic
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
application.properties To configure
# Turn on basic check , Set login user name and password
security.basic.enabled=true
spring.security.user.name=admin
spring.security.user.password=admin
Eureka Client transformation
Follow eureka When connecting, you should bring your user name and password
#eureka.client.serviceUrl.defaultZone=http://localhost:9876/eureka/
eureka.client.serviceUrl.defaultZone=http://admin:[email protected]:9876/eureka/
At this time, the login page needs to enter the user password
http://localhost:9876/
4. Service renewal to keep alive
When the client starts thinking eureka After registering its own service list , You need to send a heartbeat to eureka service To prove that he is still alive , When eureka After receiving this heartbeat request, you will know that the client is still alive , Will maintain this Service list information of the client . Once the client fails to send the heartbeat to eureka Server side , Now eureka You may think that your client has hung up , It is possible to delete the service from the list of services fall .
About the configuration of renewal and survival
Client configuration
# Client configuration
# Renewal of service , The interval between heartbeats
eureka.instance.lease-renewal-interval-in-seconds=30
# If the heartbeat time was sent before ,90 Seconds did not receive a new heartbeat , Services will be excluded
eureka.instance.lease-expiration-duration-in-seconds=90
# Express eureka client How often do I get the service registration information , The default is 30 second
eureka.client.registry-fetch-interval-seconds=30
Server configuration
# Server configuration
# Self-protection model , When the network partition appears 、eureka When too many clients are lost in a short period of time , Will enter self-protection mode , That is, a service does not send a heartbeat for a long time ,eureka It will not be deleted except , The default is true
eureka.server.enable-self-preservation=true
#Eureka Server During operation, it will count the percentage of heart failure in 15 Whether it is low within minutes On 85%, If lower 85%,Eureka Server These instances will be protected
eureka.server.renewal-percent-threshold=0.85
#eureka server Time interval to clean up invalid nodes , Default 60000 millisecond , namely 60 second
eureka.server.eviction-interval-timer-in-ms=60000
5. Eureka Health detection
Eureka The default health check is to check whether the service connection is UP still DOWN Of , Then the client will only call Status as UP State Service , But in some cases , Although the service connection is good , But it is possible that some of this service Some interfaces are not normal , Maybe due to the need to connect Redis,mongodb perhaps DB There is a problem that causes the interface call to fail , So theoretically, although the service can be invoked normally , But it is not a healthy service . So we need to deal with this Do custom health detection for the situation .
application.properties To configure
Turn on health detection
# Health detection
eureka.client.healthcheck.enabled=true
Custom health detection code
@Configuration
public class MicroWebHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// This state is whether the database is connected OK
if(UserController.canVisitDb) {
// Business identification , More db,redis, mysql And so on to get an identification
return new Health.Builder(Status.UP).build();
} else {
return new Health.Builder(Status.DOWN).build();
}
}
}
jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
6. Service offline
For example, in some cases, the service host is unexpectedly down , Which means that the service can't be given to eureka Heartbeat information , however eureka Rely on maintaining the service without receiving a heartbeat 90s, Here 90s There may be client-side calls To the service , This may cause the call to fail . So we must have a mechanism that can manually and immediately put down the service Be sure to follow eureka Clear... From the list of services , Avoid being called to by the service caller .
Call the interface of the service offline : This interface calls eureka The interface of the server
http://localhost:9876/eureka/apps/micro-order/localhost:micro-order:8765
delete request
Be careful :
If the service is not shut down during the test , There will always be a heartbeat , Cause manual offline failure
In addition, stop manually idea The service will be removed directly , Can't keep alive 90s, Because it is a normal shutdown , The client automatic service is offline
You can simulate abnormal downtime by yourself through the following commands
windows
netstat -nao | findstr 8765
taskkill /f /pid 19016 # here eureka There are still services in the service list of , It's time to live , eureka It will also be deleted
linux
ps -aux | grep 8765
kill -9 19016
Pause the service interface
PUT http://localhost:9876/eureka/apps/micro-order/localhost:micro-order:8765?value=OUT_OF_SERVICE
Online service
PUT http://localhost:9876/eureka/apps/micro-order/localhost:micro-order:8765?value=UP
7. Eureka High availability
Eureka The architecture of hot backup is as follows :
There are many in the whole micro service eureka service , Every eureka Services are all replicated , Will register the client into Copy the service to eureka From other nodes in the cluster . In fact, it's simply eureka Each node is mutually Copy .
The specific configuration is as follows :
Port is 9878 Of eureka The server registers itself to 9877 Of eureka Server side
# Multiple are separated by commas
server.port=9877
eureka.client.serviceUrl.defaultZone=http://localhost:9878/eureka/
Port is 9877 Of eureka The server registers itself to 9878 Of eureka Server side
# Multiple are separated by commas
server.port=9878
eureka.client.serviceUrl.defaultZone=http://localhost:9877/eureka/
The configuration file
application-9877.properties
application-9878.properties
When starting, start according to the specified configuration file
java -jar netflix-eureka-server-1.0-SNAPSHOT.jar --spring.profiles.active=9877 --server.port=9877
java -jar netflix-eureka-server-1.0-SNAPSHOT.jar --spring.profiles.active=9878 --server.port=9878
This is the configuration
eureka.client.serviceUrl.defaultZone=http://admin:[email protected]:9877/eureka/
边栏推荐
- Brief explanation of depth first search (with basic questions)
- Illustrated network: what is the hot backup router protocol HSRP?
- 毕业总结
- CUDA basic knowledge
- 【webrtc】m98 ninja 构建和编译指令
- 选择排序与冒泡排序模板
- Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure
- SDP中的SPA
- Objective-C member variable permissions
- STM32 external DHT11 display temperature and humidity
猜你喜欢
JSON string conversion in unity
Getting started with the go language is simple: go implements the Caesar password
MySQL maxscale realizes read-write separation
Wechat official account web page authorization
Go 语言入门很简单:Go 实现凯撒密码
laravel admin里百度编辑器自定义路径和文件名
AAAI2022 | Word Embeddings via Causal Inference: Gender Bias Reducing and Semantic Information Preserving
MySQL is dirty
MySQL one master multiple slaves + linear replication
Msgraphmailbag - search only driveitems of file types
随机推荐
Reduce function under functools
SQL statement strengthening exercise (MySQL 8.0 as an example)
logistic regression
拼夕夕二面:说说布隆过滤器与布谷鸟过滤器?应用场景?我懵了。。
1289_FreeRTOS中vTaskSuspend()接口实现分析
JVM family -- heap analysis
深度优先搜索简要讲解(附带基础题)
'2'&gt;' 10'==true? How does JS perform implicit type conversion?
Getting started with the go language is simple: go implements the Caesar password
渗透实战-SQLServer提权
用于TCP协议交互的TCPClientDemo
Aperçu du code source futur - série juc
[paddleseg source code reading] paddleseg calculates Miou
Objective-C member variable permissions
XSS prevention
2022-07-03:数组里有0和1,一定要翻转一个区间,翻转:0变1,1变0。 请问翻转后可以使得1的个数最多是多少? 来自小红书。3.13笔试。
MySQL one master multiple slaves + linear replication
渗透实战-guest账户-mimikatz-向日葵-sql提权-离线解密
STM32 external DHT11 display temperature and humidity
Simple dialogue system -- text classification using transformer