Microservices Learning Notes
Microservices architecture is an architectural approach that aims to decouple a solution by breaking its functionality down into discrete services. Its primary purpose is to divide functionality among discrete services, thereby reducing system coupling and providing more flexible service support.
Spring Cloud Microservices
Spring Cloud version comparison https://github.com/spring-cloud/spring-cloud-release/wiki/Spring-Cloud-Hoxton-Release-Notes
- A microservice is an architectural style
- An application is split into a group of small services
- Each service runs in its own process, meaning it can be deployed and upgraded independently
- Services communicate with each other using lightweight HTTP
- Services are split according to business functions
- Services can be deployed independently using a fully automated deployment mechanism
- Decentralized, autonomous services. Services can use different languages and different storage technologies
Service Decomposition
Split a monolithic architecture into multiple services according to functional modules
Considerations when decomposing:
Each microservice must not duplicate business logic
Data between microservices must be independent; do not access another microservice's database
Expose your own business functionality as an interface for other microservices to call
I. Eureka Registry
Eureka solves the problem of addresses when making calls and the problem of checking service health. It can also provide load balancing, automatic registration, and heartbeat checks to monitor service health.
There are two roles in Eureka:
- Server: a separately deployed Eureka registry
- Records service information
- Monitors heartbeats
- Client: each microservice instance
- Service provider: registers its information with Eureka and sends a heartbeat every 30 seconds
- Service consumer: retrieves the provider list from the server by service name, performs load balancing, and selects one provider to call
Set Up the Eureka Registry Server
- Create a module whose dependencies are managed by the parent project, inherit the parent project's version, and add the dependencies.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Add
@EnableEurekaServerto the startup class.Modify the yml file (purpose: register itself with the service registry so that multiple registries can communicate with each other).
server:
port: 10086
spring:
application:
name: eureka-server
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
Setting Up the Eureka Registry Client (Registering a Service with the Registry)
- Add the client dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- Modify the yml file (Purpose: register itself with the registry so that multiple registries can communicate with each other).
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
Use the service registry to obtain the service list and load balance across the services
Change the original
localhost:8081to the service nameuser-service.Add
@LoadBalancedto the method that creates theRestTemplatebean.
Ribbon implements load balancing here. Ribbon also resolves the actual address to access based on the service name.
@LoadBalancedintercepts allRestTemplaterequests (LoadBalancerInterceptor).
II. Ribbon Load Balancing
Modify the load balancing rule
- Configure it as a bean (global; cannot be specified for a particular service).
@Bean
public IRule randomRule(){
return new RandomRule();
}
- Through a YML file (you can specify a service and a load-balancing method)
'user-service':
ribbon:
NFLoadBalancerRuLeClassName: com.netflix.Loadbalancer.RandomRuLe
Ribbon Lazy-Loading Issue
Lazy loading waits until the first request arrives before loading the load-balancing client, which can result in a longer response time for the first request.
Changing to eager loading resolves this issue.
Eager-Loading Configuration
ribbon:
eager-load:
enabled: true #开启饥饿加载
clients: 'user-service' #指定饥饿加载的服务
#多个服务时
clients:
- 'user-service'
- 'order-service'
III. Nacos Registry
An Alibaba product that is now a component of Spring Cloud, with richer features than Eureka
Comparison of Eureka and Nacos (registry features only)
| Similarities | Differences |
|---|---|
| Both support service registration and service discovery | Nacos supports active health checks of providers by the server: ephemeral instances use heartbeats, while persistent instances use active checks |
| Both support provider heartbeats for health checks | Ephemeral instances are removed if their heartbeats fail; persistent instances are not removed |
| Nacos supports actively pushing notifications when the service list changes, so service list updates are more timely | |
| Nacos clusters use AP mode by default. When a cluster contains persistent instances, it uses CP mode; Eureka uses AP mode |
The Nacos server is deployed separately
# 配置java环境
# 启动nacos
/nacos/bin/startup.sh -m standalone
# 查看输出文件打开后台网页
http://192.168.6.66:8848/nacos/index.html
Nacos Service Registration
<!-- 父工程中引入SpringCloudAlibaba的管理依赖 --->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 子工程中引入nacos依赖 --->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Configure the Registry Center Address
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.6.66:8848
Nacos is now part of Spring Cloud, which defines the interface specification for service registration and discovery, making it easier to modify.
Nacos Service Hierarchical Storage Model
Each service can have many instances, which may be distributed across different regions. To prioritize matching services in the same region, instances are grouped into clusters by region.
Service calls should use services in the local cluster whenever possible, as cross-cluster calls have higher latency.
If the local cluster is unavailable, other clusters can be accessed.
Configure the Cluster Name
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.6.66:8848
cluster-name: SD
Configure Ribbon Load-Balancing Rules
com.alibaba.cLoud.nacos.ribbon.NacosRule
Load Balancing Based on Nacos Weights
Edit the corresponding instance in the Nacos console and adjust its weight. The range is [0–1].
During a canary upgrade, you can first bring the new version online to handle a small number of requests and test its stability, then adjust its weight to the normal level.
Then set the old version’s weight to 0. Once it stops receiving requests, shut down the old service. The canary rollout is complete.
Namespace Environment Isolation
Nacos structure
Namespace > Group > Service/Data > Cluster > Instance
Different namespaces can be used to isolate services from one another. This is generally suitable for separating development and production environments.
Configure a Namespace
Create a namespace in the Nacos console, copy its ID, and configure it in the service.
spring: cloud: nacos: discovery: namespace: 5ba5c782-35ad-479f-b861-76e8121e2dd0
Ephemeral Instances
An ephemeral instance is automatically destroyed when it goes offline, and its health status is not actively checked.
For a non-ephemeral instance, Nacos actively checks its health status, and the instance is not automatically destroyed.
spring:
cloud:
nacos:
discovery:
ephemeral: false
IV. Nacos Configuration Management
Implement hot reloading of configuration files
1. Create a Configuration File
Create a configuration file in the Nacos console
2. Centralized Configuration Management
To have the service read the Nacos configuration first when starting up, configure it in
bootstrap.yml
Add the configuration management client dependency
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
Create the bootstrap.yml File
spring:
application:
name: user-service
profiles:
active: dev
cloud:
nacos:
server-addr: 192.168.6.66:8848
config:
file-extension: yaml
3. Implement Hot Updates
Use the
@Valueinjection annotation and add the@RefreshScopeannotation to the class.If you use
@ConfigurationPropertiesfor injection, updates happen automatically.
4. Multi-Environment Configuration
At startup, the service reads multiple configuration files.
Read order
ervicename.extension > servicename-profile.extension > local
Priority
servicename-profile.extension > servicename.extension > local
You can add shared configuration to the corresponding configuration files listed earlier.
5. Nacos Cluster
Set up the database table structure to enable data sharing.
Configure each node in the Nacos cluster.
Rename
cluster.conf.exampletocluster.conf, and modify the port number inapplication.properties.Add the addresses of all Nacos nodes at the end of the file, and delete the instance data.
Modify
application.propertiesto add the database configuration:spring.datasource.platform=mysql
db.num=1
url username password .....
After configuring all nodes, start
startup(no additional parameters are needed; it starts in cluster mode by default).Use Nginx to load-balance the addresses of the nodes.
upstream nacos-cluster{ server {ip}:{port}; ... } server{ listen 80; server_name localhost; location /nacos{ proxy_pass http://nacos-cluster; } }
V. HTTP Client Feign
1. How to Use
Add the Feign dependency.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Add the annotation to the startup class
@EnableFeignClients
Write the Clients Class
@FeignClient("user-service")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
Direct Injection Call
@Service
public class OrderService {
@Resource
private OrderMapper orderMapper;
@Resource
private RestTemplate restTemplate;
@Resource
private UserClient userClient;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2.调用Feign查询用户信息
User user = userClient.findById(order.getUserId());
order.setUser(user);
// 4.返回
return order;
}
}
Feign Load Balancing
Ribbon is integrated into the Feign dependencies to provide load balancing.
Custom Feign Configuration
feign.client.config.{scope}.{config}={value}
scope > default (global) / service name
In general, it is recommended to disable the latter, Basic.
feign.Logger.Level
Change the log level
Includes four different levels: NONE, BASIC, HEADERS, FULLfeign.codec.Decoder
Response result parser
Parses the results of remote HTTP calls, for example, converting a JSON string into a Java object.feign.codec.Encoder
Request parameter encoding
Encodes request parameters so they can be sent via HTTP requests.feign.Contract
Supported annotation format
Defaults to Spring MVC annotations.feign.Retryer
Failure retry mechanism
Retries failed requests. There is no retry mechanism by default, but Ribbon retries are used.
Optimizing Feign Connection Performance
By default, Feign uses URLConnection as its HTTP client (it does not support connection pooling).
Alternatives: ApacheHttpClient, OKHttp (both support connection pooling).
1. Introducing Feign HttpClients
<!--httpClient的依赖-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2. Configure the connection pool
feign:
httpclient: / okhttp:
enabled: true # 开启feign对HttpClient的支持
max-connections: 200 # 最大连接数
max-connections-per-route: 50 # 每个路径最大连接数
3. Feign Best Practices
Inheritance: Define an interface for the Controller, then have the Feign Client inherit that interface (high coupling)
Extraction: Create a separate module to manage the Client code independently, and have services include that module (includes more content)
It is recommended to extract a separate module for maintenance.
- Create a new module, such as feign-api
- Add the spring-cloud-starter-openfeign dependency and write the client and POJO
- In services that need to use the client, add the feign-api dependency
- Enable @EnableFeignClients, specify the corresponding package path, and then inject and use the clients object
When there are few clients, it is recommended to specify the class directly to reduce the creation of unnecessary component objects
VI. Gateway
Gateway functions: identity authentication, permission verification, load balancing, and rate limiting;
1. Setting Up a Gateway Service
Create a Maven service module and add the dependencies.
<dependency>
<grouplId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2. Configure Gateway Routing
server:
port: 10010
spring:
application:
name: gateway
cloud:
nacos:
server-addr: localhost:8848
gateway:
routes:
- id: user-service #路由的ID必须唯一
uri: lb://user-service # 路由的目标地址
predicates: #路由断言
- Path=/user/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/order/**
3. Access Testing
Omitted
Route Predicate Factory
Converts assertion rule strings in the configuration file into route matching conditions.
For example, the Path field is handled by the PathRoutePredicateFactory.

Gateway Route Filters
Processes requests or responses for a route. Filters configured under a route apply only to that route.
defaultFiltersapply to all routes.
defaultFilters example:
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Red, Default-Blue
- PrefixPath=/httpbin
Global Filters
Global filters are implemented through interfaces.
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("custom global filter");
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -1;
}
}
Filter Execution Logic
Route filters, DefaultFilter, and GlobalFilter
All three types of filters are converted to GatewayFilter through adapters and added to a collection, then sorted by order.
The order of defaultFilter and route filters is sorted from 1 upward according to their declared order (each scope is sorted separately).
If the order values are the same, the priority is: defaultFilter > route filters > globalFilter.
Cross-Origin Requests in the Gateway
In a microservice architecture, all requests are received by the Gateway, so cross-origin requests need to be configured in the Gateway. However, the Gateway uses WebFlux rather than Servlets, so the configuration differs.
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost:8090"
- "http://www.leyou.com"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
VII. Docker Container Technology
Basic Commands
/article/1703786714981638146
Dockerfile
A Dockerfile is a text file containing a series of instructions, each of which creates a layer.

Dockerfile example:
FROM ubuntu:22.04
ENV JAVA_HOME=/usr/local/jdk-17.0.10/
COPY ./target/jdk-17.0.10/ $JAVA_HOME
ENV PATH=$PATH:$JAVA_HOME/bin
FROM jdk17
ENV APPLICATION_DIR=/data
COPY ./target/docker-demo-0.0.1-SNAPSHOT.jar $APPLICATION_DIR/
EXPOSE 8080
ENTRYPOINT java -jar $APPLICATION_DIR/docker-demo-0.0.1-SNAPSHOT.jar
DockerCompose
Compose v1 must be installed separately. Compose v2 is integrated into Docker as a plugin.
Container orchestration for quickly deploying distributed applications
Compose file example
version: "3.8"
services:
nacos:
image: nacos/nacos-server
environment:
MODE: standalone
ports:
- "8848:8848"
mysql:
image: mysql:5.7
environment:
MYSQL-ROOT-PASSWORD: 123
volumes:
- "mysql-data:/var/lib/mysql"
- "mysql-conf:/etc/mysql/conf.d"
user-service:
build: ./user-service
depends_on:
- nacos
- mysql
- gateway
order-service:
build: ./order-service
depends_on:
- nacos
- mysql
- gateway
gateway:
build: ./gateway
depends_on:
- nacos
ports:
- "10010:10010"
volumes:
mysql-data:
mysql-conf:
Private Repository
Create a private repository and configure it as a trusted Docker repository.
Images:
registry,joxit/docker-registry-ui:staticPush:
docker tag nginx:latest host:prot/nginx:1.0
docker pushPull:
docker pull host:prot/nginx:1.0Specific steps omitted.
VIII. Asynchronous Communication - MQ
Event-driven architecture: Events are sent to the broker, which notifies all services subscribed to those events.
Advantages of asynchronous communication: handles traffic spikes, decouples services, isolates failures, and increases throughput.
Disadvantages: high performance requirements for the broker, greater complexity, and difficulty tracking the flow.
MQ, or message queue, is the broker in an event-driven architecture.
Common message queue software includes RabbitMQ (reliable, stable, and high-performing), RocketMQ, ActiveMQ, and Kafka.
RabbitMQ
docker run \
-e RABBITMQ_DEFAULT_USER=reboot \
-e RABBITMQ_DEFAULT_PASS=123456 \
--name mq \
--hostname mq1 \
-p 15672:15672 \
-p 5672:5672 \
-d rabbitmq:3.13.0-management
<img src="/api/file/44c66b59ef6d435e88607544a1e4bfdf.png" alt="image-20240331102749599" style="zoom: 33%;" />
Spring AMQP
Using MQ in the traditional way is too cumbersome; Spring Boot has already provided auto-configuration for us.
Simple Mode Example
- Add the dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- Configure the MQ connection information in yml.
spring:
rabbitmq:
addresses: localhost
port: 5671
virtual-host: /
username: reboot
password: 123456
listener:
simple:
prefetch: 1 //消息预取
- Send a Message to the Queue
@Resource
private RabbitTemplate rabbitTemplate;
@Test
void name() throws InterruptedException {
String queueName = "simple.queue";
String message = "Hello Spring AMQP";
rabbitTemplate.convertAndSend(queueName,message);
}
- Receive messages
@Component
@Slf4j
public class RabbitMQListener {
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueueMessage(String message) {
log.info(message);
}
}
Publish-Subscribe Pattern
In the original pattern, messages were sent directly to queues. This is changed to sending them to an exchange, which then sends them to the corresponding queues.
Features: Exchanges support three delivery modes: routing, broadcast, and forwarding.
If delivery from the exchange fails, the message is lost; exchanges do not provide storage.
Broadcast Mode
- Define the exchange and queues, then bind them.
Declare Using Beans
@Configuration
public class FanoutConfig {
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange("wds.fanout");
}
@Bean
public Queue fanoutQueue1() {
return new Queue("fanout.queue1");
}
@Bean
public Binding fanoutBinding1(FanoutExchange fanoutExchange, Queue fanoutQueue1) {
return BindingBuilder
.bind(fanoutQueue1)
.to(fanoutExchange);
}
@Bean
public Queue fanoutQueue2() {
return new Queue("fanout.queue2");
}
@Bean
public Binding fanoutBinding2(FanoutExchange fanoutExchange, Queue fanoutQueue2) {
return BindingBuilder
.bind(fanoutQueue2)
.to(fanoutExchange);
}
}
- Subscription Messages
@RabbitListener(queues = "fanout.queue1")
public void listenSimpleQueue1Message(String message) {
log.info("queue1:{}",message);
}
@RabbitListener(queues = "fanout.queue2")
public void listenSimpleQueue2Message(String message) {
log.info("queue2:{}",message);
}
- Publish a message
@Test
void name2() {
String exchangeName = "wds.fanout";
String message = "Hello Spring AMQP by wds";
rabbitTemplate.convertAndSend(exchangeName,"", message);
}
- Successfully received the message
com.wds.mq.listener.RabbitMQListener : queue2:Hello Spring AMQP by wds
com.wds.mq.listener.RabbitMQListener : queue1:Hello Spring AMQP by wds
Routing Pattern
- Declare queue, exchange, and binding relationships, etc.
Declare Using Annotations
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "direct.exchange", type = ExchangeTypes.DIRECT),
key = {"blue", "black"}
))
public void listenExchangeDirectMessage(String message) {
log.info("direct queue1:{}", message);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue2"),
exchange = @Exchange(name = "direct.exchange", type = ExchangeTypes.DIRECT),
key = {"1", "2"}
))
public void listenExchangeDirectMessage2(String message) {
log.info("direct queue2:{}", message);
}
- Publish a Message
@Test
void name3() {
String exchangeName = "direct.exchange";
String message = "Hello Spring AMQP by wds";
rabbitTemplate.convertAndSend(exchangeName,"blue", message);
rabbitTemplate.convertAndSend(exchangeName,"1", message);
}
Topic Pattern
The difference between a topic and a routing key is that each word in a topic must be separated by .
Wildcards can be used when binding exchanges to queues
represents zero or more words
- represents one word
Usage:
Declaration: Change the exchange type to Topic and the key to a topic-type key
The other APIs remain unchanged
Message Type Conversion
By default, the JDK’s default serialization method is used, which has poor readability and takes up a lot of space
It is generally changed to JSON
- Import the dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
- Create Bean
@Configuration
public class MessageConfig {
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}
}
9. Elasticsearch
An open-source distributed search engine that can provide search, log statistics, analysis, system monitoring, and other functions
- Elastic Stack
- A technology stack centered around Elasticsearch, including Beats, Logstash, Kibana, and Elasticsearch
- Lucene
- An Apache-based open-source search engine library that provides a search engine API
Inverted Index
Documents are tokenized in advance, and an index is created for the tokens. When searching, the search criteria are tokenized, and the corresponding documents are then retrieved based on those tokens.
The inverted index is an important principle behind the Elasticsearch search engine.
Create and Start
Create an ES network to make it easier to add components later.
docker network create es-net运行elasticsearch
docker run -d --name es --net es-net --privileged -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -v es-data:/usr/share/elasticsearch/data -v es-config:/usr/share/elasticsearch/config -v es-plugins:/usr/share/elasticsearch/plugins elasticsearch:7.12.1 修改conf中的jvm配置,可以抑制内存占用Deploy Kibana
docker run -d --name kibana -v kibana-conf:/usr/share/kibana/config --net es-net -p 5601:5601 kibana:7.12.1# 安装ik 分词插件 elasticsearch-plugin install https://github.com/infinilabs/analysis-ik/releases/download/v7.12.1/elasticsearch-analysis-ik-7.12.1.zip # 重启容器 docker restart es// Use the tokenizer to tokenize the text POST /_analyze { "text": "Lick bricks for the motherland, Java. I really appreciate it.", "analyzer": "ik_smart" }analyzer有两种:
ik_smat:智能模式,分词的数量较少。
ik_max_word:详细模式,分词数量较多。
IK分词器 配置
修改/usr/share/elasticsearch/config 或者数据卷 es-config中xml配置文件,修改对应文件并重启es服务器即可生效
可增加词语或停用词语
索引库 Mapping约束
Mapping是对索引库中的文档进行约束,常见的mapping属性有
- type:字段数据类型 (字段的数据类型没有数组的概念,但是可有多个值)
- 字符串:text(可以分词的文本),keyword(精确值,分词无意义)
- 数值: long、integer、short、byte、double、float
- 布尔:boolean
- 日期:date
- 对象:object
- index: 是否创建索引,默认为true
- analyzer:使用哪种分词器创建倒排索引
- properties: 某字段的子字段
- 更多属性参考文档:https://www.elastic.co/guide/en/elasticsearch/reference/7.17/mapping-params.html
索引库操作
# 创建索引库语法
put /索引库名称
{
"mapping": {
"properties": {
"字段名": {
"type": "text",
"analyzer": "ik_smart"
},
"字段名2": {
"type": "keyword",
"index": "false"
},
"字段名3": {
"properties": {
"子字段": {
"type": "keyword",
},
}
}
}
//more ...
}
}
# 创建索引库
PUT /test
{
"mappings": {
"properties": {
"info": {
"type": "text",
"analyzer": "ik_smart"
},
"email": {
"type": "keyword",
"index": false
},
"name": {
"type": "object",
"properties": {
"firstName": {
"type": "keyword",
"index": false
},
"lastName": {
"type": "keyword",
"index": false
}
}
}
}
}
}
# 查询索引库信息
GET /test
# 修改索引库,增加新字段 (不允许修改已有的字段)
PUT /test/_mapping
{
"properties":{
"age":{
"type": "integer"
}
}
}
# 删除索引库
DELETE /test
Document Operations
# 新增文档 语法
# 如果不指定ID,将会生成随机的ID,不便查询
POST /索引库名/_doc/文档id
{
"字段1": "值1"
}
# 示例
POST /test/_doc/1
{
"info": "人生苦短我用Java",
"email": "[email protected]",
"name": {
"firstName": "张",
"lastName": "三"
},
"age": 20
}
# 查询文档
GET /test/_doc/1
# 删除文档
DELETE /test/_doc/1
# 修改文档
# 第一种方法 全量修改,该操作会将原有的文档删除,然后新增该文档 (如果ID不存在,则直接新增)
PUT /索引库名/_doc/文档id
{
"字段1": "值1"
}
# 局部修改
POST /test/_update/1
{
"doc":{
"字段1": "新值 "
}
}
RestClient Client
Java uses RestClient to interact with ES
<!-- 对于Springboot项目 必须在参数pom参数中覆盖依赖的版本,否则将会有部分版本不受控制 -->
<elasticsearch.version>7.12.1</elasticsearch.version>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
Connecting to Elasticsearch and Index Operations
public class HotelConstants {
public static final String MAPPING_TEMPLATE = "DSLJSON 略"
}
class HotelDemoApplicationTests {
private RestHighLevelClient client;
@BeforeEach
void init() {
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://localhost:9200")
));}
@Test
void test() throws IOException {
System.out.println("client = " + client);}
@Test
void createHotelIndex() throws IOException {
// 1 Create a request object
CreateIndexRequest request = new CreateIndexRequest("hotel");
// 2 Prepare the DSL code
request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
// 3 Send the request
client.indices().create(request, RequestOptions.DEFAULT); }
@AfterEach
void destroy() throws IOException {
if (client == null) return;
this.client.close();
}
}
Operations Documentation
Add New Document
//添加文档到索引库 1.指定索引库名,文档ID,文档数据 2.发送请求。
IndexRequest request = new IndexRequest("hotel").id("{id}");
request.source("{json_data}",XContentType.JSON);
client.index(request,RequestOptions.DEFAULT);
//通过数据库查询并插入索引库示例
Hotel hotel = hotelService.getById(61083L);
HotelDoc hotelDoc = new HotelDoc(hotel);
// Create an index instance and document ID
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId() + "");
// Prepare the SL code
request.source(new ObjectMapper().writeValueAsString(hotelDoc), XContentType.JSON);
// Send the request
client.index(request, RequestOptions.DEFAULT);
Query Documentation
@Test
void testGetDocument() throws IOException {
// 发送查询请求
GetRequest request = new GetRequest("hotel", "61083");
GetResponse documentResponse = client.get(request, RequestOptions.DEFAULT);
// 获取查询结果
String json = documentResponse.getSourceAsString();
System.out.println("json = " + json);
HotelDoc hotelDoc = new ObjectMapper().readValue(json, HotelDoc.class);
System.out.println("hotelDoc = " + hotelDoc);
}
Batch Operations
// 通过Bulk操作减少请求次数,提高整体性能
@Test
void testBulk() throws IOException {
BulkRequest requests = new BulkRequest();
List<Hotel> list = hotelService.list();
for (Hotel hotel : list) {
requests.add(new IndexRequest("hotel").id(hotel.getId() + "")
.source(new ObjectMapper().writeValueAsString(new HotelDoc(hotel)),XContentType.JSON));
}
client.bulk(requests, RequestOptions.DEFAULT);
}
Query Operations
void handleResponse(SearchResponse response) throws IOException {
SearchHits searchHits = response.getHits();
TotalHits totalHits = searchHits.getTotalHits();
System.out.println("totalHits = " + totalHits);
for (SearchHit hit : searchHits.getHits()) {
HotelDoc hotelDoc = new ObjectMapper().readValue(hit.getSourceAsString(), HotelDoc.class);
System.out.println(hotelDoc.getName());
}
}
@Test
void testMatchAll() throws IOException {
SearchRequest request = new SearchRequest("hotel");
request.source().query(QueryBuilders.matchAllQuery());
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
@Test
void testMatch() throws IOException {
SearchRequest request = new SearchRequest("hotel");
// request.source().query(QueryBuilders.matchQuery("all", "如家"));
// request.source().query(QueryBuilders.multiMatchQuery("酒店","name"));
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.termQuery("city", "上海"));
boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(250));
request.source().query(boolQueryBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
}
Sorting and Pagination
@Test
void testSortAndPage() throws IOException {
SearchRequest request = new SearchRequest("hotel");
request.source().query(QueryBuilders.matchAllQuery());
request.source().from(10).size(20);
request.source().sort("price", SortOrder.DESC);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
Highlights
@Test
void testHighLight() throws IOException {
SearchRequest request = new SearchRequest("hotel");
request.source().query(QueryBuilders.matchQuery("all","如家"));
request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits searchHits = response.getHits();
TotalHits totalHits = searchHits.getTotalHits();
System.out.println("totalHits = " + totalHits);
for (SearchHit hit : searchHits.getHits()) {
Map<String, HighlightField> fields = hit.getHighlightFields();
HighlightField field = fields.get("name");
if (field == null) {return;}
String highLightName = field.getFragments()[0].string();
HotelDoc hotelDoc = new ObjectMapper().readValue(hit.getSourceAsString(), HotelDoc.class);
hotelDoc.setName(highLightName);
System.out.println(hotelDoc.getName() + "\t" + hotelDoc.getPrice());
}
}
Aggregations
DSL Query Basic Syntax
Full-Text Search Queries
# 语法格式
GET /indexName/_seach
{
"query":{
"type":{
"condition":"value"
}
}
}
# type : match_all 查询所有
{
"query":{
"match_all": {}
}
}
# type : match 匹配某个字段
{
"query":{
"match": {
"all":"如家"
}
}
}
# type : multi_match 匹配某些字段
# (多个字段在查询时,性能较低,建议使用copy_to)
{
"query":{
"match": {
"query":"如家",
"fields":["brand","name","business"]
}
}
}
Exact Queries
Exact queries are generally used to search fields such as keywords, numbers, dates, and booleans.
term: Search by value
range: Search by value range
# term 查询
GET /hotel/_search
{
"query":{
"term":{
"city":{
"value":"上海"
}
}
}
}
# range 查询
GET /hotel/_search
{
"query":{
"range":{
"price":{
"gte": 1000,
"lte": 3000
}
}
}
}
#gte 大于等于,gt 大于
#lte 小于等于,lt 小于
Geographical Queries
Query by latitude and longitude
- geo_bounding_box: Query documents where a geo_point field falls within a rectangular area.
GET /hotel/_search
{
"query": {
"geo_bounding_box":{
"location":{
"top_left":{
"lat": 31.1,
"lon": 121.5
},
"bottom_right":{
"lat": 30.9,
"lon": 121.7
}
}
}
}
}
- geo_distance: Searches for documents within a specified distance of a center point.
GET /hotel/_search
{
"query":{
"geo_distance":{
"distance":"15km",
"location":"31.21,121.5"
}
}
}
Relevance scoring algorithms:
TF (term frequency) (scores for multiple tokens are not reasonable enough)
TF-IDF (inverse document frequency) (greatly affected by term frequency)
BM25 algorithm (less affected by term frequency)
Function Score Query
Boost certain relevant documents using this method.
# 为 “如家” 品牌加分
GET /hotel/_search
{
"query": {
"function_score": {
"query": {
"match": {
"all": "外滩"
}
},
"functions": [
{
"filter": {
"term": {
"brand": "如家"
}
},
"weight": 10
}
],
"boost_mode": "sum"
}
}
}
Compound Queries: Boolean Query
The three types of compound queries:
- must: must match
- should: optional match
- must_note: must match, but does not contribute to scoring
- filter: must match, but does not contribute to scoring (reduces performance overhead)
GET /hotel/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"name": "如家"
}}],
"filter": [{
"geo_distance": {
"distance": "10km",
"location": {
"lat": 31.21,
"lon": 121.5
}}}],
"must_not": [
{
"range": {
"price": {
"gte": 400
}}}]}}}
Search Result Processing
Sorting
Elasticsearch supports sorting search results. By default, results are sorted by
_score.Supported sort types include keyword, numeric, geographic coordinates, and date.
// 排序写法
GET /indexName/_search
{
"query":{
"match_all":{}
},
"sort":{
"field":"desc" //排序字段和排序方式 ASC和DESC
}
}
// 根据地理坐标排序
GET /hotel/_search
{
"query": {
"match_all": {}
}
, "sort": [
{
"_geo_distance": {
"location": {
"lat": 31.034315,
"lon": 121.611691
},
"order": "asc"
}}]}
Pagination
Specify the starting index with the
fromparameter and the number of documents to retrieve withsize. When no pagination parameters are specified, the query returns only the first 10 results by default.
GET /hotel/_search
{
"query":{
"match_all":{}
},
"sort":{
"price":"asc"
},
"from":0,
"size":100
}
Deep Pagination
For pagination, Elasticsearch has to retrieve all the data each time and then slice the results, which consumes too much memory. Elasticsearch limits queries to the first 10,000 records.
For very specific requirements, you can sort the results and use
search_afterto retrieve the 10,000th record, then use that record as the condition for the next query. Alternatively, usescroll(deprecated).
Highlight
GET /hotel/_search
{
"query": {
"match": {
"all": "如家"
}
},
"highlight": {
"fields": {
"name": {
"require_field_match": "false"
}
}
}
}
Aggregations
Three types of aggregations:
Bucket: Similar to MySQL
GROUP BY;Terms,Date...Metric: Similar to MySQL aggregate functions;
Avg,Max,Min,Stats(calculates multiple metrics at once)Pipeline: Performs aggregations on top of other aggregations
Supported aggregation data types:
Keyword,date,boolean, and numeric
Bucket Aggregations
Three elements: aggregation name, aggregation type, aggregation field
GET /hotel/_search
{
// 对聚合的数据进行限制
"query": {
"range": {
"price": {
"lte": 200
}
}
},
// size 0 不展示文档
"size": 0,
"aggs": {
"brands": {
"terms": {
"field": "brand",
"size": 10, // 聚合数据条数
"order": {
"_count": "desc" //默认排序规则
}
}
}
}
}
Metric Aggregation Metric
GET /hotel/_search
{
"size": 0,
"aggs": {
"brands": {
"terms": {
"field": "brand",
"size": 10,
"order": {
"scores.avg": "desc" // 根据子聚合的数据进行排序
}
},
"aggs": { // 子聚合 分组后对每个分组进行计算
"scores": { // 子聚合名称
"stats": { // 聚合类型
"field": "score" // 聚合字段
}
}
}
}
}
}
Pinyin Tokenizer
Install the Pinyin Tokenizer
elasticsearch-plugin install https://github.com/infinilabs/analysis-pinyin/releases/download/v7.12.1/elasticsearch-analysis-pinyin-7.12.1.zip
Testing the Pinyin tokenizer
POST /_analyze
{
"text": ["如家酒店还不错"],
"analyzer": "pinyin"
}
Disadvantages of the Pinyin Tokenizer
- The results contain only Pinyin.
- The Pinyin tokens are individual characters.
Solution
A custom analyzer: In Elasticsearch, an analyzer consists of three components:
Character filter: Performs basic text processing, such as deleting or replacing characters.
Tokenizer: Splits text into tokens, for example, using ik_smart.
Token filter: Performs further processing, such as changing case or converting text to Pinyin.
These three components are applied in order, from top to bottom.
How to Create a Custom Analyzer
To create a custom analyzer, configure it using
settingswhen creating the index.
PUT /test
{
“settings":{
"analysis":{
"analyzer":{
"my_analyzer":{
"tokenizer":"ik_max_word",
"filter":"pinyin"
}
}
}
}
}
Further Customizing the Tokenizer
The current tokenizer has many shortcomings. It needs further customization before it can be used in production.
PUT /test
{
"settings":{
"analysis":{
"analyzer":{
"my_analyzer":{ //自定义分词器
"tokenizer":"ik_max_word",
"filter":"pinyin_"
}
},
"filter":{
"pinyin_":{
"type":"pinyin", // 配置拼音分词器的参数
"keep_full_pinyin":false,
"keep_joined_full_pinyin":true,
"keep_original":true,
"remove_duplicated_term":true,
"none_chinese_pinyin_tokenize":false
}
}
}
},
"mappings": {
"properties": {
"name":{
"type": "text",
"analyzer": "my_analyzer",
"search_analyzer": "ik_max_word" // 指定搜索使用的分词器
//搜索时,不适合使用拼音分词,会出现多余的无用信息
}
}
}
}
// 测试索引库中的分词器
POST /test/_analyze
{
"text": ["如家酒店还不错"],
"analyzer": "my_analyzer"
}
Autocomplete
To enable autocomplete for a field, its type should be
completion.Completion data is an array of strings.
Create an autocomplete index library
PUT test2
{
"mappings": {
"properties": {
"title":{
"type": "completion"
}
}
}
}
Populate Data
POST test2/_doc
{
"title": ["Sony", "WH-1000XM3"]
}
POST test2/_doc
{
"title": ["SK-II", "PITERA"]
}
POST test2/_doc
{
"title": ["Nintendo", "switch"]
}
Query Completion
GET /test2/_search
{
"suggest": {
"titleSuggest": {
"text": "s",
"completion": {
"field": "title",
"skip_duplicates": true,
"size": 10
}
}
}
}
Integrating Autocomplete and Pinyin Segmentation
GET /hotel/_mapping
DELETE /hotel
PUT /hotel
{
"settings": {
"analysis": {
"analyzer": {
"text_analyzer": {
"tokenizer": "ik_max_word",
"filter": "pinyin_"
},
"completion_analyzer": {
"tokenizer": "ik_smart",
"filter": "pinyin_"
}
},
"filter": {
"pinyin_": {
"type": "pinyin",
"keep_full_pinyin": false,
"keep_joined_full_pinyin": true,
"keep_original": true,
"remove_duplicated_term": true,
"none_chinese_pinyin_tokenize": false
}
}
}
},
"mappings": {
"properties": {
"address": {
"type": "keyword",
"index": false
},
"brand": {
"type": "keyword",
"copy_to": "all"
},
"business": {
"type": "keyword"
},
"city": {
"type": "keyword",
"copy_to": "all"
},
"id": {
"type": "keyword"
},
"isAD": {
"type": "boolean"
},
"location": {
"type": "geo_point"
},
"name": {
"type": "text",
"analyzer": "text_analyzer",
"search_analyzer": "ik_smart",
"copy_to": "all"
},
"pic": {
"type": "keyword"
},
"price": {
"type": "integer"
},
"score": {
"type": "integer"
},
"starName": {
"type": "keyword",
"copy_to": "all"
},
"all": {
"type": "text",
"analyzer": "text_analyzer",
"search_analyzer": "ik_smart"
},
"suggestion": {
"type": "completion",
"analyzer": "completion_analyzer"
}
}
}
}
GET /hotel/_search
{
"suggest": {
"suggestions": {
"text": "h",
"completion": {
"field": "suggestion"
}
}
}
}
Implementing Data Synchronization Between the Database and Elasticsearch
Synchronous Updates
Services call one another to update ES document data.
Disadvantages: slow, tightly coupled
Advantages: simple to implement
Asynchronous Updates via a Message Queue (Recommended)
High performance, loose coupling, moderate complexity
Configure a TopicExchange and two queues, each listening for database update messages and database deletion messages via different routing keys.
Consumer: MQ configuration, message processing
Producer: message-sending logic
Updating ES Documents by Listening to MySQL BinLog
Very high performance, no coupling, but high complexity and dependent on database configuration
10. Sentinel Microservice Protection
In a microservice architecture, the health of one service may affect the entire system (the cascading failure problem).
To address this, thread isolation, traffic control, and circuit-breaking strategies are typically introduced to prevent and avoid this problem.
Service protection technologies: Sentinel (Alibaba), Hystrix (Netflix, no longer actively maintained)
Installation
1.下载Jar文件
https://github.com/alibaba/Sentinel/releases/
2.运行jar文件
java -jar -Dserver.port=8080
3.默认用户名密码都是sentinel,可以修改jar包中文配置文件
Usage
- Add the Sentinel dependency.
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
- Configuration
spring:
cloud:
sentinel:
transport:
dashboard: sentinel:9999
- View Status
For configured services, health information will be synchronized to the Sentinel dashboard when the first request is received.
Rate Limiting (Preventive Measures)
Traffic control adjusts the rate at which network packets are sent. Requests arriving at any given time are often random and unpredictable, while the system’s processing capacity is limited. Traffic must therefore be controlled according to the system’s capacity. As a traffic regulator, Sentinel can limit the maximum QPS of random requests as needed to ensure that services run healthily.
Flow control modes:
- Direct: When an API reaches the rate-limiting condition, limit it directly (for example, when it reaches a certain number of clicks)
- Associated: When an associated resource reaches its threshold, limit the current resource
- Link: Record traffic only on a specified path. If traffic to a specified resource from an entry resource reaches the threshold, apply rate limiting. This is API-level rate limiting.
Flow control effects:
Fail fast: When the threshold is exceeded, fail quickly and throw an exception
Warm Up: A warm-up mode suited to services that have just started. When traffic surges, certain initialization operations may take a long time and could cause service problems. Warm-up mode gradually increases traffic over time to provide protection.
Queueing: Unlike fail-fast mode, this allows requests to wait in a queue. However, requests with an expected wait time that is too long will still fail. Queueing is generally used for traffic shaping.
Hotspots:
More fine-grained rate-limiting rules can be applied based on request parameters. Exceptions can be configured for hotspot parameters to allow higher traffic.
Isolation and Degradation
For microservice protection, rate limiting helps prevent service problems. However, when a service is already having problems, isolation and degradation are generally used to prevent the affected service from impacting other microservices.
Isolation:
Configure a thread pool for the relevant business logic on the caller side to prevent abnormal threads from consuming too many resources and making the service unavailable.
Configure call rules for the service caller. Service calls are often implemented using Feign, so the client must configure both Feign and Sentinel.
- Enable Sentinel in the Feign client.
feign:
sentinel:
enabled: true
- Logic for handling write failures
@Slf4j
public class UserClientFallbackFactory implements FallbackFactory<UserClient> {
@Override
public UserClient create(Throwable cause) {
return new UserClient() {
@Override
public User findById(Long id) {
log.error("UserClient: findById:" + cause);
return null;
}
};
}
}
@FeignClient(value = "user-service", fallbackFactory = UserClientFallbackFactory.class)
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
public class FeignConfig {
@Bean
public UserClientFallbackFactory userClientFallbackFactory() {
System.err.println("create UserClientFallbackFactory");
return new UserClientFallbackFactory();
}
}
@EnableFeignClients(basePackages = "com.wds",defaultConfiguration = FeignConfig.class)
public class OrderApplication {...}
Circuit-Breaker Fallback
For services with a high exception rate, trip the circuit breaker for the service and block its requests until the service recovers.
Three states:
- closed The circuit breaker is closed, allowing all requests through while monitoring their status.
- open The circuit breaker is open, blocking requests and failing fast.
- half-open After the circuit-breaker timeout expires, allow one request through. If it succeeds, close the circuit breaker.
Circuit-breaking strategies
- Slow-call ratio Track the proportion of timed-out requests
- Exception ratio Track the proportion of requests that result in exceptions
- Exception count Track the number of exceptions
Rule Persistence
Omitted
XI. Distributed Transactions
ACID Principles of Transactions
A — Atomicity: Operations in a transaction either all succeed or all fail.
C — Consistency: Ensure the database's integrity constraints and consistency constraints are maintained.
I — Isolation: Transactions operating on the same resource must not occur simultaneously.
D — Durability: Changes to the database are saved permanently, regardless of whether a failure occurs.
Distributed Systems — CAP Theorem
For distributed systems:
C — Consistency: Users accessing any node must receive consistent data.
A — Availability: Healthy services must respond; they must not time out or reject requests.
P — Partition tolerance: If the system's services become partitioned, the entire system must continue providing service externally.
The three CAP properties cannot all be satisfied at the same time; only two can be satisfied. The trade-offs involved in CAP led to the BASE theory.
Distributed Systems — BASE Theory
Basically Available: When a distributed system fails, it is acceptable to lose some availability, as long as core functionality remains available.
Soft State: Brief inconsistencies are allowed for a certain period of time.
Eventually Consistent: Although strong consistency cannot be guaranteed, data must ultimately become consistent after the soft state ends.
Install and Configure Seata
Download and extract it, then modify the configuration in the registry file in the conf directory.
注册中心
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "DEFAULT_GROUP"
namespace = ""
cluster = "SH" # 一定要指定,不要用default,有BUG会导致IP问题
username = "nacos"
password = "nacos"
}
配置中心
type = "nacos"
nacos {
serverAddr = "127.0.0.1:8848"
namespace = ""
group = "SEATA_GROUP"
username = "nacos"
password = "nacos"
dataId = "seataServer.properties"
}
Configure the corresponding settings in Nacos:
seataServer.properties
# 数据存储方式,db代表数据库
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
# 事务、日志等配置
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
# 客户端与服务端传输方式
transport.serialization=seata
transport.compressor=none
# 关闭metrics功能,提高性能
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
Then restore the corresponding database files, run seata-server.bat in the bin directory, and start the Seata service.
Integrating Seata into a Service
For microservices that need to use Seata, add the dependency.
<seata.version>1.4.2</seata.version>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<artifactId>seata-spring-boot-starter</artifactId>
<groupId>io.seata</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>${seata.version}</version>
</dependency>
Configure the yml file
seata:
registry:
type: nacos
nacos:
server-addr: nacos:8848
namespace: ""
group: DEFAULT_GROUP
application: seata-server
username: nacos
password: nacos
tx-service-group: seata-demo
service:
vgroup-mapping:
seata-demo: default
XA Mode
XA mode: After each service’s RM finishes execution, it does not commit immediately. Instead, the transaction coordinator TC checks the status and then commits or rolls back all services together.
Advantages and disadvantages: This preserves the database’s ACID properties and also relies on the database’s transaction capabilities. Resources must remain occupied until all called services have finished executing, and can only then be released.
seata:
data-source-proxy-mode: XA #事务模式
Add the @GlobalTransactional annotation to methods that need to start a global transaction.
Note that it should be added to the caller’s method. The called service will be managed automatically, so there is no need to add it to the called method.
AT Mode
Difference from XA mode: The transaction is committed immediately after execution completes, so resources are locked for a shorter period. Rollbacks after failure are implemented using data snapshots.
XA provides strong consistency, while AT provides eventual consistency.
Disadvantage: The intermediate state is a soft state and provides eventual consistency.
Snapshots can affect performance, but perform much better than locking resources.
Snapshots are stored in the undo_log table in the microservice database.
seata:
data-source-proxy-mode: AT #事务模式
TCC Mode
TCC (try commit cancel) mode does not use database locks. It commits immediately after execution and does not occupy resources.
Phase one: Execute the corresponding logic.
Phase two: Based on the status of phase one, commit or roll back.
Points to note: empty rollback (cancel), hanging (try), and idempotency (cancel) issues.
Implementing TCC mode is relatively complex. You need to implement all three TCC operations and create corresponding tables to coordinate the TCC logic.
DROP TABLE IF EXISTS `account_freeze_tbl`;
CREATE TABLE `account_freeze_tbl` (
`xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`user_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`freeze_money` int(11) UNSIGNED NULL DEFAULT 0,
`state` int(1) NULL DEFAULT NULL COMMENT '事务状态,0:try,1:confirm,2:cancel',
PRIMARY KEY (`xid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = COMPACT;
@LocalTCC
public interface AccountTCCService {
@TwoPhaseBusinessAction(name = "deduct", commitMethod = "confirm", rollbackMethod = "cancel")
void deduct(
@BusinessActionContextParameter(paramName = "userId") String userId,
@BusinessActionContextParameter(paramName = "money") int money);
boolean confirm(BusinessActionContext ctx);
boolean cancel(BusinessActionContext ctx);
}
@Service
@Slf4j
public class AccountTCCServiceImpl implements AccountTCCService {
@Resource
private AccountMapper accountMapper;
@Resource
private AccountFreezeMapper accountFreezeMapper;
@Override
public void deduct(String userId, int money) {
// 从Seata上下文中获取事务ID
String xid = RootContext.getXID();
// 悬挂
AccountFreeze suspensionFreeze = accountFreezeMapper.selectById(xid);
if (suspensionFreeze != null) {
return;
}
// 扣减余额,创建冻结对象,记录状态并存储
accountMapper.deduct(userId, money);
AccountFreeze accountFreeze = new AccountFreeze();
accountFreeze.setUserId(userId);
accountFreeze.setFreezeMoney(money);
accountFreeze.setState(AccountFreeze.State.TRY);
accountFreeze.setXid(xid);
accountFreezeMapper.insert(accountFreeze);
}
@Override
public boolean confirm(BusinessActionContext ctx) {
String xid = ctx.getXid();
int count = accountFreezeMapper.deleteById(xid);
return count == 1;
}
@Override
public boolean cancel(BusinessActionContext ctx) {
String xid = ctx.getXid();
AccountFreeze accountFreeze = accountFreezeMapper.selectById(xid);
// 空回滚
if (accountFreeze == null) {
AccountFreeze freeze = new AccountFreeze();
freeze.setXid(xid);
freeze.setState(AccountFreeze.State.CANCEL);
int count = accountFreezeMapper.insert(freeze);
return count == 1;
}
// 幂等性
if (accountFreeze.getState() == AccountFreeze.State.CANCEL) {
return true;
}
// 常规回滚
accountMapper.refund(accountFreeze.getUserId(), accountFreeze.getFreezeMoney());
accountFreeze.setFreezeMoney(0);
accountFreeze.setState(AccountFreeze.State.CANCEL);
int account = accountFreezeMapper.updateById(accountFreeze);
return account == 1;
}
}
Replace the logic in the original service with the logic in TCC.
Saga Mode
Saga mode is a long-running transaction solution provided by SEATA. It consists of two phases:
Phase 1: Commit the local transaction directly.
Phase 2: If successful, do nothing; if it fails, roll back by implementing failure compensation logic.
There are no locks or isolation, so dirty writes can occur.
The duration of the soft state is uncertain, resulting in poor timeliness.
You need to implement a state machine and compensation logic.
Seata High Availability
The requirement is to be able to switch to another cluster without restarting the service when a Seata node in the cluster encounters a problem.
- Configure the cluster configuration file in Nacos and create
client.properties.
# 事务组映射关系
service.vgroupMapping.seata-demo=SH
# 以下均为默认值
service.enableDegrade=false
service.disableGlobalTransaction=false
# 与TC服务的通信配置
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
# RM配置
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
# TM配置
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
# undo日志配置
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
client.log.exceptionRate=100
- Modify the microservice to read configuration from Nacos.
seata:
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
group: SEATA_GROUP
data-id: client.properties
Restart the microservices. Which TC cluster each microservice connects to is now determined uniformly by Nacos's client.properties.
XII. Distributed Caching
Problems with standalone Redis:
- Data loss - Redis data persistence
- Concurrency limitations - Set up a master-replica cluster to enable read/write separation
- Storage capacity limitations - Set up a sharded cluster and use the slot mechanism to scale dynamically
- Failure recovery - Use Redis Sentinel for health monitoring and automatic recovery
Key technologies: persistence, master-replica, Sentinel, sharded clusters
Redis Persistence
RDB Mode
RDB stands for Redis Database Backup file.
Simply put, it records all the data in Redis memory to disk. When Redis restarts after a failure, it reads the snapshot file from disk to restore the data.
By default, the Redis service performs an RDB operation when it shuts down (not when it crashes).
Backup command
save
# 由redis主进程来执行RDB,会阻塞所有命令
bgsave
# 子进程后台执行备份操作,不会阻塞命令
RDB configuration
#自动备份 900秒内如果至少有一个key被修改,则执行bgsave,如果是 save "" 表示禁用RDB
save 900 1
save 300 10
save 60 10000
rdbcompression no # 是否压缩 压缩消耗CPU,节省磁盘空间
dbfilename dump.rdb #文件存储名称
dir ./ #文件保存目录
Why doesn't bgsave affect data writes?
The page table is forked and set to read-only. New writes need to create a new copy to operate on, while the old data is used for backup.
AOF Mode
AOF (Append Only File)
Every Redis operation is recorded in the AOF file. It can be viewed as a log file, but unlike a typical log file, AOF can be compacted to remove meaningless operation records.
AOF is disabled by default and must be enabled by changing the configuration. The following settings apply to AOF operations.
appendonly yes
appendfilename "appendonly.aof"
# aof文件记录的频率, 立即记录到文件/每秒记录一次/由操作系统决定
appendfsync always / everysec (默认) / no
aof-related commands
bgrewirteaof
# 将aof文件中的命令进行压缩,用最少的命令,达到相同的效果
# 设置自动执行机制
auto-aof-rewrite-parcentage 100 #体积增长100%后执行
auto-aof-rewrite-min-size 64mb #体积增长多少后执行
Redis Primary–Replica
Start multiple Redis nodes. Run slaveof on the replica nodes to specify the primary. Separating reads and writes can significantly improve read performance.
Related commands
slaveof 主节点ip 主节点端口
slaveof no one (脱离从节点状态)
<strong>Note</strong>: The replicaof command was added after version 5.0 and has the same effect as salveof.
# 无法访问 检查配置文件
bind 0.0.0.0 -::
protected-mode no
Configuration File
bind 0.0.0.0 -::
protected-mode no
port 6379
dbfilename dump.rdb
rdb-del-sync-files no
dir ./
pidfile /var/run/redis_7001.pid
appendonly no
appendfilename "appendonly.aof"
appenddirname "appendonlydir"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
aof-timestamp-enabled no
tcp-backlog 511
timeout 0
tcp-keepalive 300
daemonize no
loglevel notice
logfile ""
databases 16
always-show-logo no
set-proc-title yes
proc-title-template "{title} {listen-addr} {server-mode}"
locale-collate ""
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync yes
repl-diskless-sync-delay 5
repl-diskless-sync-max-replicas 0
repl-diskless-load disabled
repl-disable-tcp-nodelay no
replica-priority 100
acllog-max-len 128
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
lazyfree-lazy-user-del no
lazyfree-lazy-user-flush no
oom-score-adj no
oom-score-adj-values 0 200 800
disable-thp yes
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-listpack-entries 512
hash-max-listpack-value 64
list-max-listpack-size -2
list-compress-depth 0
set-max-intset-entries 512
set-max-listpack-entries 128
set-max-listpack-value 64
zset-max-listpack-entries 128
zset-max-listpack-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
jemalloc-bg-thread yes
To configure the cluster with Docker, you need to use a custom image that specifies a configuration file when starting Redis. The default image cannot start Redis.
FROM redis
COPY redis.conf /usr/local/etc/redis/redis.conf
CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ]
Redis Sentinel Cluster
Configure the Sentinel cluster and Redis cluster. The Sentinel cluster monitors the health of the Redis cluster and directs master-slave elections.
Configure the yml file.
spring:
redis:
sentinel:
master:mymaster
nodes:
- 192.168.150.101:27001
- 192.168.150.101:27002
- 192.168.150.101:27003
Configure Redis write operations to target the master node
Redis sharded cluster
A sharded cluster requires a relatively large number of servers.
For Redis versions before 6,
For Redis 6 and later, cluster management is integrated into redis-cli. The format is as follows:
redis-cli --cluster create --cluster-replicas 1 192.168.150.101:7001 192.168.150.101:7002 192.168.150.101:7003 192.168.150.101:8001 192.168.150.101:8002 192.168.150.101:8003
Command description:
redis-cli --clusteror./redis-trib.rb: Indicates a cluster operation command.create: Indicates cluster creation.--replicas 1or--cluster-replicas 1: Specifies that each master in the cluster has 1 replica. In this case, the value returned by节点总数 ÷ (replicas + 1)is the number of masters. Therefore, the first n nodes in the node list are masters, and the remaining nodes are slave nodes, randomly assigned to different masters.
You can view the cluster status with the command:
redis-cli -p 7001 cluster nodes
When operating on the cluster, add the -c parameter to redis-cli.
redis-cli -c -p 7001
XIII. Microservices MQ
Questions:
- Message reliability: How can you ensure that a message is consumed at least once?
- Delayed messages: How can you implement delayed message delivery?
- High availability: How can you avoid single points of failure in MQ?
- Message backlog: How can you resolve message backlogs that prevent timely consumption?