Spring Boot related notes
- @localServerPort: Port to start the service, automatically assigned to the defined variable
Means of communication between services
- Synchronous communication call
- REST Http Communication (External)- Only strings in the network can penetrate the firewall (JSON data passing)
JAX-RS
SpringBoot
Copy the code
- RPC remote procedure call (fast internally on the Intranet)
Thrift(Cross-language Framework) Dubbo(JAVA only)Copy the code
- Asynchronous communication call
Kafka(no Broker requires no persistence of messages) Notify MessageQueueCopy the code
Solution for service hanging
- Retry mechanism
- Current limiting
- Circuit breakers
- Load balancing
- Degrade (local cache)
Conditions for distributed locks
- In a distributed deployment system, a method can only be executed by one thread on one machine at a time
- Highly available lock acquisition and lock release
- High-performance lock acquisition and lock release
- Reentrant feature (high concurrency without affecting data)
- Lock failure mechanism to prevent deadlocks
- Non-blocking lock feature (timeout return message)
Use of Spring Boot
- Select New Project in IDEA and select Spring Initializr
Unit testing of Spring Boot
- Add annotations
## Enable unit tests to detect Spring Boot configurations
@SpringBootTest(classes = HelloSpringBootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
Copy the code
Change the banner pattern when Spring Boot starts
Spring Boot configuration file
Logging Configuration for Spring Boot (LogBack)
Other template engines provided by Spring Boot
- FreeMarker
- Groovy
- Mustache
- Thymeleaf
- Velocity
- Beetl
Spring Boot integrates Thymeleaf
- Introduce the Thymeleaf dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
## Add non-strict HTML schema< the dependency > < groupId >.net. Sourceforge. Nekohtml < / groupId > < artifactId > nekohtml < / artifactId > < version > 1.9.22 < / version > </dependency>Copy the code
- Add the YML configuration for Thymeleaf
spring:
thymeleaf:
cache: false # Turn caching off during development or you won't be able to see live pages
mode: LEGACYHTML5 # use strict HTML
encoding: UTF-8
servlet:
content-type: text/html
Copy the code
- Create index.html and introduce the Thymeleaf tag configuration
<! DOCTYPE html SYSTEM"http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"></html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span th:text="${user.username}"</span> </body> </ HTML >Copy the code
Spring Boot integration myBatis(Durid connection Pool)
- Configure mysql and DURID connection pools
- Add mysql and durID dependencies
< the dependency > < groupId > com. Alibaba < / groupId > < artifactId > druid - spring - the boot - starter < / artifactId > < version > 1.1.10 < / version > </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>Copy the code
- Add mysql yML configuration
Spring: a datasource: druid: url: JDBC: mysql: / / 47.112.215.6:3306 / myshop/useUnicode =true&characterEncoding=utf-8&userSSL=false
username: root
password: 123456
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
driver-class-name: com.mysql.jdbc.Driver
Copy the code
- Configuration tk. Mybatis
- Introduction of depend on
< the dependency > < groupId > tk. Mybatis < / groupId > < artifactId > mapper - spring - the boot - starter < / artifactId > < version > 2.0.2 < / version > </dependency>Copy the code
- Add the Tk.mybatis configuration
mybatis:
type-aliases-package: com.mrchen.hello.springboot.mybatis.entity
mapper-locations: classpath:mapper/*.xml
Copy the code
- Create a generic parent interface (myMapper.class)
* <p>Title: MyMapper</p> * <p>Description: </p> * * @author Mrchen * @version 1.0.0 * @date 2020/5/8 */ public interface MyMapper<T> extends Mapper<T>, MySqlMapper { }Copy the code
- MyBatis (PageHelper)
- Introduction of depend on
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> The < version > 1.2.5 < / version > < / dependency >Copy the code
- Generate the code using the Maven plugin for MyBatis
- Add the POM plug-in configuration
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> The < version > 1.3.5 < / version > < configuration > < configurationFile >${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> < version > 3.4.4 < / version > < / dependency > < / dependencies > < / plugin >Copy the code
- Configure the Generatorconfig.xml file
<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE generatorConfiguration PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="jdbc.properties"/>
<context defaultModelType="flat" id="Mysql" targetRuntime="MyBatis3Simple">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/ > <! -- Generated Java file encoding --> <property name="javaFileEncoding" value="UTF-8"/ > <! All Mappwe inherit this root --> <! -- This is a place to pay attention to, and you configure the Application above MapperScan mapper package scan not in the same folder, such as my my package scan is @mapperscan ("com.jzj.tkdemo.dao"BaseMapper should not be placed in Mapper's package scan, for the following reasons -> <plugintype="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.MyMapper"/>
</plugin>
<jdbcConnection
driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.username}"
password="${jdbc.password}"> </jdbcConnection> <! --> <javaModelGenerator targetPackage="com.mrchen.hello.springboot.mybatis.entity"
targetProject="src/main/java">
<property name="trimStrings" value="true"/> </javaModelGenerator> <! <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> </sqlMapGenerator> <! ANNOTATEDMAPPER: creates ANNOTATEDMAPPER with Annotation (SQL generated in Annotation), not XML. 2. XMLMAPPER: Mapper interface will be generated, and the interface is completely dependent on XML. 3. This package is com.jzj.tkdemo.dao. Do not put the above BaseMapper below ittype="XMLMAPPER"
targetPackage="com.mrchen.hello.springboot.mybatis.mapper"
targetProject="src/main/java"> </javaClientGenerator> <! -- User is the database table, UserPO is the entity class you want to generate from the report --> <! -- Configure the tables to be generated, % represents all --> <table tableName="%"> <! Mysql > <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
</context>
</generatorConfiguration>
Copy the code
- Run the mybatis -Generator: Generate plug-in
- Spring-boot-mybatis use test
- At the entrance to add scan mapper annotation @ MapperScan (basePackages = “com. Mrchen. Hello. Springboot. Mybatis. Mapper”)
Use of Spring Cloud
- Create unified dependency management
hello-spring-cloud-dependencies
Copy the code
- Service Registration and Discovery (Eureka)
- Spring Boot Boot class add annotations (Eureka server)
- Add the application.yml configuration
spring:
application:
name: hello-spring-cloud-eureka
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
Copy the code
- Creating a service provider
- Spring Boot Boot class add annotations (Eureka client)
- Add the application.yml configuration
spring:
application:
name: hello-spring-cloud-service-admin
server:
port: 8762
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code
- Creating a Service Consumer (Ribbon)
- Add annotations to the Spring Boot Boot class (Eureka consumer)
- Add the application.yml configuration
spring:
application:
name: hello-spring-cloud-web-admin-ribbon
thymeleaf:
cache: false
mode: LEGACYHTML5
encoding: UTF-8
servlet:
content-type: text/html
server:
port: 8764
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code
- Ribbon (load balancing) + RestTemplate(Issuing Rest requests) requests other Eureka service interfaces
- Create service consumers (Feign- default with ribbon)
- Add annotations to the Spring Boot Boot class
- Add the application.yml configuration
spring:
application:
name: hello-spring-cloud-web-admin-feign
thymeleaf:
cache: false
mode: LEGACYHTML5
encoding: UTF-8
servlet:
content-type: text/html
server:
port: 8765
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code
- The ribbon uses Hystrix fuses
- Add annotations to SpringBoot
- Adds a fuse method annotation and specifies the fuse method
- Use fuses in FEIGN (fuses come with FEIGN)
- Enable the Feign fuse application.yml configuration
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code
- Added the feign fuse specified fuse implementation and the annotation parameter fallback
- Fuse instrument panel (monitoring fuse)
- Add POM dependencies
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
Copy the code
- Add the EnableHystrixDashboard annotation to the Spring Boot Boot class
- Adding a Configuration Class
- Access the dashboard path
http://localhost:8765/hystrix
Copy the code
- Unified Access Interface using Routing Gateway (API Gateway – ZUul)
- Add POM dependencies
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
Copy the code
- Add annotations to the Spring Boot Boot class
- Add the application.yml configuration
spring:
application:
name: hello-spring-cloud-zuul
server:
port: 8769
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
zuul:
routes:
api-a:
path: /api/a/**
serviceId: hello-spring-cloud-web-admin-ribbon
api-b:
path: /api/b/**
serviceId: hello-spring-cloud-web-admin-feign
Copy the code
- Callback when configuring network management routes fails
- Create service filtering for the routing gateway (inheriting ZuulFilter)
- Four methods of routing filters
## fiterType(when the filter is executed)Pre: before a route. Routing: before a route. Post: after a route## filterOrderFilter order (0,1,2...)## shouldFilterWhether filtering is required (true.false)
## runThe specific business code for the filterCopy the code
Spring Cloud Distributed Configuration Center (Cloud Configuration -Spring Cloud Config)
- After adding the Spring Cloud distributed configuration center, all configuration files are named bootstrap.xml
## Apollo
## Spring Cloud Config
Copy the code
- Build the cloud configuration server
- Add poM configuration
- Add an open annotation to the Spring Boot Boot class
- Add the application.yml configuration
spring: application: name: hello-spring-cloud-config cloud: config: label: master server: git: uri: http://47.112.215.6/OhMyGit/spring-cloud-config.git search - paths: respo username: @qq.com password: 365984197 365984197 server: port: 8888 eureka: client: service-url: defaultZone: http://localhost:8761/eureka/Copy the code
- Change the local configuration to cloud configuration
- Add cloud configuration client POM dependencies
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Copy the code
- Add the application.yml configuration
Spring: cloud: config: uri: http://47.112.215.6/OhMyGit/spring-cloud-config.git name: web - admin - feign label: master profile: devCopy the code
- Enable Spring Boot Profile to specify profile types (development, production, test)
- Package different cloud configurations (startup parameters) by command
Java jar - hello - spring - the cloud - web - admin - feign - 1.0.0 - SNAPSHOP. Jar -- spring. Profiles. The active = proCopy the code
- Link Tracing for Spring Cloud (ZipKin)
- Add Spring Boot Boot class annotations
- Add the application.yml configuration
spring:
application:
name: hello-spring-cloud-zipkin
server:
port: 9411
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
management:
metrics:
web:
server:
auto-time-requests: false
Copy the code
- All items that need to be tracked have dependencies and configurations added
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
spring:
zipkin:
base-url: http://localhost:9411
Copy the code
- Spring Boot Admin service monitoring
- Add Spring Boot Boot annotations
- Add application.yml configuration (server side)
spring:
application:
name: hello-spring-cloud-admin
zipkin:
base-url: http://localhost:9411
server:
port: 8084
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: ["health"."info"]
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code
- The monitored services require dependencies and configurations
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>
spring:
boot:
admin:
client:
url: http://localhost:8084
Copy the code
- Service startup sequence
Registration and discovery 2. Distributed Configuration center 3. Link Monitoring 4. Service monitoring 3. Service provider 4. Service consumer 5. API gatewayCopy the code
Better tools to use
www.bilibili.com/video/BV1mt…