SpringBoot
What is micro service
What is the difference between microservices and the past
Why is SpringBoot suitable for microservice framework
Lack of SpringBoot or microservice
springBoot startup process
How to automatically assemble and customize the configuration of springBoot
First, there are a few notes
@Configuration: declare a configuration class
@ConfigurationProperties: used to convert XXX The objects in the YML configuration file correspond to the xxproperties class, which is equivalent to injecting @ value one by one
@EnableConfigurationProperties: this annotation is used to automatically configure properties and correspond configuration classes to xxproperties
@ConditionalOnxxx: judge whether all subsequent conditions are met, and inject bean s if they are met
- @The enable autoconfiguration annotation introduces an autoconfiguration import selector
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fyf5v6wo-1600227354630) (C: \ users \ Zheng \ appdata \ roaming \ typora \ typora user images \ image-20200828084936566. PNG)]
[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nnkqjhoa-1600227354633) (C: \ users \ Zheng \ appdata \ roaming \ typora \ typora user images \ image-20200828091108263. PNG)]
- This searcher will use the spring factoriesloader loader to scan mete-inf / spring Files under the factories path
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-4cocopru-1600227354635) (C: \ users \ Zheng \ appdata \ roaming \ typora \ user images \ image-20200828090957214. PNG)]
In mete-inf / spring There are many configuration class paths in factories,
[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xrb8td8s-1600227354638) (C: \ users \ Zheng \ appdata \ roaming \ typora user images \ image-20200828091247951. PNG)]
- These configuration classes use the @ EnableConfigurationProperties annotation to correspond to the xxproperties configuration file class
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG frsiua60-1600227354641) (C: \ users \ Zheng \ appdata \ roaming \ typora \ typora user images \ image-20200828091351615. PNG)]
- The @ ConfigurationProperties annotation is used in the xxxproperties configuration file class to inject the properties and in the configuration file into this class
[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xzlnnbew-1600227354643) (C: \ users \ Zheng \ appdata \ roaming \ typora \ typora user images \ image-20200828091433654. PNG)]
Therefore, the user-defined configuration can be realized by modifying the attribute value in the configuration file.
How does SpringBoot make configuration simple
springBoot dependencies are in the parent project
The version number is defined in spring boot dependencies
springboot turns some functional scenarios into initiators one by one. When using, you can directly introduce the corresponding initiators
springboot will load a large number of automatic configuration classes at startup
METE-INF/spring.factories
Default configuration file. If it is not configured in this file, it needs to be configured manually
When the springboot starts, it will not be fully loaded. You need to judge whether the corresponding start initiator is introduced.
How does SpringBoot make deployment easy
- SpringBoot has built-in web containers such as tomcat and jetty
- The jar package generated by SpringBoot can be executed directly using java jar
- Spring boot provides spring boot devtools for hot deployment
@SpringBootApplication
-
Core annotations of springboot
@Spring bootconfiguration, @ enableautoconfiguration and @ ComponentScan are three annotations
@ComponentScan scans the component s and loads the bean s into the container
@EnableAutoConfiguration allows automatic configuration. Through this annotation, spring injects the required bean s into the container through [AutoConfigurationImportSelector].
@SpringBootConfiguration is equivalent to @ Configuration and is used to declare that the current class is a Configuration class. The bean object is managed by the spring container through @ bean.
@ConditionalONXXX
Indicates that the annotation will take effect only if all the conditions of the annotation are met
What does @ springbootApplication do when springboot starts
- Import all dependent jar packages into
- Declare that the startup class is a component and hand it over to the spring container for management
- Scan all component s and load them into the container
SpringApplication class
- Infer whether it is a normal project or a web project [based on dispatchServlet, servletContainer]
- Load all initializers
- Set all listeners
- Determine main class
springBoot configuration file
- Two formats [yml or properties]
- Fixed name [application.yml or application.properties]
- yaml can store objects, while properties can only store key value pairs
- Recommend yml
Syntax structure:
application.properties key=value ---------- application.yml key:Space value
application.yml
#Storage object student: name: hh age: 2 student: {name: hh,age: 3} #Array / list name: - zhagn - wang - zhao name: [zhang,wang,zhao] #map map: {k1: v1,k2: ${random.int}}
-
@ConfigurationProperties
You can use this annotation to inject objects in the yml configuration file
@ConfigurationProperties(prefix="person")
-
@PropertySource
@PropertySource(value = "classpath:test01.properties")
Used to load the specified configuration file [applicable to properties format]
-
@Vlidated
data verification
@email(message = "does not conform to email format")
private String email;
-
Priority of profile:
- config folder under project directory
- Project root directory
- config folder under classpath [resource]
- Under classpath
-
Multi environment configuration
properties format spring.profiles.active=dev ------- yml format Multiple versions can be written in the same file at the same time Define different names, using---separate use: spring: profiles: active: dev
How is the yml configuration file parsed
In mete-inf / spring There are many configuration class paths in factories,
These configuration classes use the @ EnableConfigurationProperties annotation to correspond to the xxproperties configuration file class
The @ ConfigurationProperties annotation is used in the xxxproperties configuration file class to inject the properties and in the configuration file into this class
Therefore, the user-defined configuration can be realized by modifying the attribute value in the configuration file.
integration
Consolidated database
After configuring the datasource data source in the yml configuration file
You can use the bean object of datasource to connect to the database for operation.
-
application.yml
spring: datasource: username: root password: root url: jdbc:mysql://127.0.0.1:3306/gl_itgs?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource filters: wall,ltog4j,stat
-
testControllet
@RestController public class testController { @Autowired DataSource dataSource; //Just inject JDBC template automatically @Autowired JdbcTemplate jdbcTemplate; @GetMapping("/findAll/{dmlb}") public List<Map<String, Object>> getData(@PathVariable String dmlb) throws SQLException { String sql = "select * from gl_sys_code where dmlb =" +dmlb +" limit 10"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } }
-
xxxtemplate
spring configured bean s can be used immediately, such as JDBC template
Consolidated DRUID
DRUID is a database connection pool implementation on Alibaba platform
It combines the advantages of database connection pools such as DBCP and C3P0, and adds log monitoring at the same time
Detail connection https://www.bilibili.com/video/av75233634?p=32
Integrate mybatis
Integrate spring security
Main functions: authentication, authorization
Integrate swagger
API framework
Function: online automatic generation tool for REST API documents
Run directly, and you can test the API interface online
Support multiple languages
use
-
Import jar package
swagger2,UI
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
+ to configure swaggerConfiguration ```java //Customize swagger configuration @Configuration @EnableSwagger2 public class SwaggerConfig { }
-
Custom scan package
The select method of Docket customizes the scanning package, whether it is available, etc.
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket(Environment environment) { //Available according to the project running environment settings boolean flag = true; Profiles profiles = Profiles.of("dev"); flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(flag) .select() //Specify the packages to scan .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .build(); } private ApiInfo apiInfo() { Contact DEFAULT_CONTACT = new Contact("", "", ""); return new ApiInfo( "Api Documentation", "Api Documentation", "1.0", "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList() ); } }
-
Set multiple groups
Generate multiple docketBean objects and set different group names
@Bean public Docket docket1(Environment environmen) { return new Docket(DocumentationType.SWAGGER_2).groupName("A"); } @Bean public Docket docket1(Environment environmen) { return new Docket(DocumentationType.SWAGGER_2).groupName("B"); }
-
Annotation operation
@ApiOperation("Get user") @Api(tags = "controller") @ApiParam("user id") ---- @ApiModel("User class") public class User { @ApiModelProperty("user name") private String name; @ApiModelProperty("password") private String password; } ---- @Api(tags = "controller") @RestController public class testController { @Autowired DataSource dataSource; @Autowired JdbcTemplate jdbcTemplate; @GetMapping("/findAll/{dmlb}") public List<Map<String, Object>> getData(@PathVariable String dmlb) throws SQLException { String sql = "select * from gl_sys_code where dmlb =" +dmlb +" limit 10"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } @ApiOperation("Get user") @RequestMapping(value = "/user/{id}",method = RequestMethod.GET) public String getUser(@ApiParam("user id") @PathVariable String id){ return id + ""; } }
springBoot and docker
Docker
Basic concepts
-
images
Template for creating docker
-
container
The instance after the image is started is called a container, which is an application or group of applications running independently
-
client
Connect to docker host for operation
-
host
Machine with Docker program installed
-
Warehouse
Used to save various packaged images [dockhub]
Different from virtual machine
Use steps
- Install docker
- Go to the warehouse and find the corresponding image
- Run the image with docker to generate a docker container
- The start and stop of the container is the start and stop of the software.
install
1. sudo apt-get update 2. sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ gnupg-agent \ software-properties-common 3. sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - 4. sudo apt-key fingerprint 0EBFCD88 5. sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" 6. sudo apt-get update 7. Install the latest version: sudo apt-get install docker-ce docker-ce-cli containerd.io 7. Install the specified version: Get available version information: apt-cache madison docker-ce Installation: sudo apt-get install docker-ce=<VERSION_STRING> docker-ce-cli=<VERSION_STRING> containerd.io 8. verification: docker --version Or: docker --version
use
-
retrieval
docker search mysql
-
Pull
docker pull mysql
docker pull mysql: 5.5
-
list
docker images
-
delete mirror
docker rmi
-
Start container
docker run --name -d :
docker run --name mytomcat -d tomcat:8.5-jdk11-openjdk
-
Restart container
docker restart /
-
View running containers
docker ps
-
View all containers
docker ps -a
-
Container rename
docker rename
-
Stopped container
docker stop
-
Delete container
dock rm
-
Port mapping
docker run -d -p host port number: mapping port number and image name
docker run -d -p 8888:8080 tomcat
-d: background operation
-p: port mapping
-
Container log
docker log /:
-
Enter container directory
docker exec -it /bin/bash
docker docker exec -it 968996d73e77 /bin/bash
example
Using MySQL
//Open mysql docker run -p 3307:3306 --name mysql01 -e MYSQL_ROOT_PASSWORD=000000 -d mysql:5.5 run : implement -p: Port mapping --name: Custom container name -e MYSQL_ROOT_PASSWORD: set up MySQLROOT User password -d: Background execution