Preface:

Spring Boot is designed to simplify the creation, running, debugging, and deployment of Spring applications. It can be used to focus on the development of Spring applications without paying too much attention to the configuration of XML.

In short, it provides a bundle of dependencies and has solved the dependency problem according to usage habits – habits over conventions.

Spring Boot uses Tomcat as the default server and logback to provide logging.

The main benefits of Spring Boot:

1. Faster start for all Spring developers

2. Out of the box, various default configurations are provided to simplify project configuration

3. Inline containers simplify Web projects

4. No redundant code generation and XML configuration requirements

Technology stack:

1.Java 8

2.Maven

3.Spring-boot

4.Mybatis

5.Redis

6.Lombok

7.Swagger2

8.Jenkins

9.SonarQuber

Build projects using Maven

1. Produce the base project through the SPRING INITIALIZR tool

Quickly create a spring-boot service framework by visiting: start.spring. IO /.

After initializing related information, download the compressed package. After decompression, open the project with IDEA. The directory structure of the project is as follows:

Overall process:

Access: start. Spring. IO /

Select the build tool Maven Project, Spring Boot version 1.3.2, and some basic Project information

Click Generate Project to download the Project package

IntelliJ IDEA 14 is used as an example:

Choose File — >New — >Project from Existing Sources…

Select the unzipped project folder and click OK

Click Import Project from External Model and select Maven. Click Next to finish.

If your environment has multiple versions of the JDK, note that when selecting the Java SDK, select Java 7 or later

2. Import spring-boot dependencies

When a project is initialized, the dependencies are as follows:

1. Spring-boot-starters: Core modules, including auto-configuration support, logging, and YAML

Spring-boot-starter-test: test modules, including JUnit, Hamcrest, and Mockito

3. Spring-boot-devtools: used to set hot deployment

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>Copy the code

Here we need to introduce the Web module, we need to add:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

3. Start the project

Add home control layer:

 public String index() { return "hello world!";
 }
}
Copy the code

Run the main method in DemoApplication to start the service:

Service starts, visit http://localhost:8080/index, you can see page output Hello world! .

Second, integrate Mybatis

1. Project dependency

1. Introduce the necessary dependency of mysql-connector-java to connect to mysql

2. Introduce the integration of MyBatis core dependency MyBatis -spring-boot-starter

3. Introduce tk.mybatis dependency to realize the code of adding, deleting, changing and checking the entity class

4. Introduce the PagerHelper dependency to implement paging function

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> < version > 1.3.0 < / version > < / dependency > < the dependency > < groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 5.1.43 < / version > < / dependency > < the dependency > < the groupId > tk. Mybatis < / groupId > < artifactId > mapper - spring - the boot - starter < / artifactId > < version > 1.1.3 < / version > < / dependency > <! --pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> < artifactId > pagehelper - spring - the boot - starter < / artifactId > < version > 1.1.2 < / version > < / dependency >Copy the code

2. Project configuration

Modify the application.properties file under Resources:

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=root spring.datasource.password=root Driver-class-name = com.datasource. Driver-name = com.mysql.jdbc.driver. mybatis. Type-aliases -package=com.jaycekon.demo Per. XML file scanning directory mybatis. Mapper - locations = classpath: mapper / *. Xml# hump named mybatis. Configuration. MapUnderscoreToCamelCase = true# TKM Apper tools mapper. Mappers = com. Jaycekon. Demo. Util. MyMapper mapper. The not - empty = falsemapper. Identity = MYSQL pagehelper.helperDialect=mysql pagehelper.reas`onable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSqlCopy the code

Unit testing

To create an entity class, we introduce Lombok dependencies to avoid repeated creation of data Get Set methods:

< the dependency > < groupId > org. Projectlombok < / groupId > < artifactId > lombok < / artifactId > < version > 1.16.18 < / version > <scope>provided</scope> </dependency>Copy the code

The final code for the entity class looks like this:

@Data@NoArgsConstructor@AllArgsConstructor@Accessors(chain = true)public class User { private int id; private String username; private String idCard; private String phone; private String password;
}
Copy the code

As you can see, our Java entity class code is much cleaner with the addition of Lombok.

Next, we need to create the UserMapper database processing class. Since MyMapper has already implemented the basic CRUD operations for us, we don’t need to rewrite the operations here. I can start with a method based on the user name:

@Mapperpublic interface UserMapper extends MyMapper<User> { @Select("select * from user where username=#{username}") User selectByName(String username);
}
Copy the code

The MyMapper class is in the util directory:

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
Copy the code

Note that MyMapper cannot be in the same directory as our entity class Mapper.

The test class:

@RunWith(SpringRunner.class)@SpringBootTest@MapperScan("com.Jaycekon.demo.mapper")public class UserMapperTest { @Autowired private UserMapper mapper; @Test public void testInset() { User user = new User(1, "Jaycekon","1234","1234","123"); int i = mapper.insert(user); Assert.assertNotEquals(0, i); } @Test public void testSelect(){ User user = mapper.selectByName("Jaycekon"); Assert.assertNotEquals(null,user); }}Copy the code

Third, integrate Redis

1. Related dependencies

Spring Data Redis is a Data access framework provided by Spring Boot based on Jedis. Dependencies can be configured by introducing spring-boot-starter-redis.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-redis</artifactId></dependency>
Copy the code

2. Redis configuration

1. The configuration of Spring-boot connected to the stand-alone Redis is as follows:

#REDIS (RedisProperties)# REDIS (RedisProperties)# REDIS database index (default 0) spring.redis.database=0 Port =6379# Redis server connection password (default empty) Spring.redis. Password =# Spring.redis.pool. max-active=8# Maximum connection pool waiting time (negative value indicates no limit) Spring.redis.pool. max-wait=-1# Spring.redis.pool. max-idle=8# Spring.redis.pool. min-idle=0# Spring.redis.pool. timeout=0

2, Spring-boot connection Sentinel cluster configuration:

#REDIS (RedisProperties)# REDIS database index (default 0) spring.redis.database=0# REDIS server address #spring.redis.host=localhost# Port =6379# Redis server connection password (default is empty) Spring.redis. Password =# Spring.redis.pool. max-active=8# Maximum connection pool waiting time (negative value indicates no limit) Spring.redis.pool. max-wait=-1# Spring.redis.pool. max-idle=8# Spring.redis.pool. min-idle=0# Spring.redis. timeout=0# Sentry listens to Redis Server name spring. Redis. Sentinel. Master = cn – test – master# sentry configuration list spring. Redis.. Sentinel nodes = localhost: 26379, localhost: 36379, l ocalhost:46379

3. Redis operation tool class

1. StringRedisTemplate utility class

The StringRedisTemplate utility class handles string-level Redis operations. Once the configuration is written, objects can be injected directly through Autowried.

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class ApplicationTests {  @Autowired private StringRedisTemplate stringRedisTemplate; @ Test public void Test () throws the Exception {/ / save the string stringRedisTemplate opsForValue (). The set (" aaa ", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); }}Copy the code

RedisTemplate<Object,Object> utility class

Handles most of the serialization, and here I’ve wrapped a simplified Redis utility class that can be optimized later.

@componentPublic class RedisComponent {@autowired // string template, StringRedisTemplate is a subset of RedisTemplate private StringRedisTemplate StringRedisTemplate; private Logger logger = LoggerFactory.getLogger(RedisComponent.class); Private RedisTemplate<Object, Object> RedisTemplate; public void set(String key, String value) { ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue(); boolean bExistent = this.stringRedisTemplate.hasKey(key); if (bExistent) { logger.info("this key is bExistent!" ); } else { ops.set(key, value); } } public String get(String key) { return this.stringRedisTemplate.opsForValue().get(key); } public void del(String key) { this.stringRedisTemplate.delete(key); } public void sentinelSet(String key, Object object) { redisTemplate.opsForValue().set(key, JSON.toJSONString(object)); } public String sentinelGet(String key) { return String.valueOf(redisTemplate.opsForValue().get(key)); }}Copy the code

Integrate Swagger2

1, Add Swagger2 dependency:

< the dependency > < groupId > IO. Springfox < / groupId > < artifactId > springfox - swagger2 < / artifactId > < version > 2.7.0 < / version > </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> The < version > 2.7.0 < / version > < / dependency >Copy the code

Create Swagger2 config class

Create a Swagger2 configuration class at the application. Java level:

@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket webApi() { return new Docket (DocumentationType SWAGGER_2). GroupName (" DemoAPI interface document "). ApiInfo (apiInfo ()). The select () .apis(RequestHandlerSelectors.basePackage("com.Jaycekon.demo.controller")) .paths(PathSelectors.any()).build(); } /** Swagger2;} /** Swagger2;} /** Swagger2 @APIIMPLICITParam: Used in the @APIIMPLicitParams annotation to specify aspects of a request parameter. ParamType: Where the parameter is placed. Header --> Request parameter fetch: @requestParam path (used for restful interfaces) --> @pathVariable body (not used) form (not used) name: Parameter name dataType: parameter type required: whether the parameter must be passed value: meaning of the parameter defaultValue: defaultValue of the parameter @apiresponses: used to represent a set of responses @apiresponse: Used in @apiresponses, generally used to express an error response message code: a number, such as 400 message: a message, such as "request parameters not filled in" Response: the class that threw the exception @apiModel: Describe information about a Model (typically used during POST creation in @requestBody scenarios where request parameters cannot be described using the @APIIMPLICITParam annotation) @APIModelProperty: Private ApiInfo ApiInfo () {return new ApiInfoBuilder().title("Demo builds RESTful APIs with Swagger2 ") . The description (" WeChat card reader services "). The contact (new contact (" Jaycekon ", "http://petstore.swagger.io/v2/swagger.json", "[email protected]")). The version (" 1.0 "). The build (); }}Copy the code

Add annotations to the interface where the Api needs to be generated:

@api (tags =" test case ")@RestController@RequestMapping(value="/users") // Configure the following mappings to be under /users, Public class UserController {@apiOperation (value=" obtain user list ", notes="") @requestMapping (value={""}, method= RequestMethod.GET) public List<User> getUserList() { return new ArrayList<>(); } @apiOperation (value=" create User ", notes=" create User from User object ") @apiIMPLICITParam (name =" User ", value=" User detail entity User ", required = true, dataType = "User") @RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestBody User user) { return "success"; } @apiOperation (value=" get user details ", notes=" get user details based on URL ID") @apiIMPLICITParam (name =" id", value=" user ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { return new User(); } @apiOperation (value=" update user details ", notes=" specify update object based on URL ID, @apiIMPLICITParams ({@APIIMPLICITParam (name = "id", value = "user id", Required = true, DataType = "Long"), @APIIMPLICITParam (name = "user", value = "user detail entity user", required = true, dataType = "User") }) @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @RequestBody User user) { return "success"; } @apiOperation (value=" delete user ", notes=" specify delete object based on URL ID") @APIIMPLICITParam (name =" id", value=" user ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { return "success"; }}Copy the code

Complete the above code to add on, start the Spring Boot program, visit: http://localhost:8080/swagger-ui.html

. You will see the RESTful API page shown above. We can click on the specific API request again. Taking the POST/Users request as an example, we can find the Notes information configured in the above code and the description of the parameter user, as shown in the figure below.

Spring-boot: Quickly set up the microservice framework

Four, access Jenkins&SonarQube

After the project framework is set up, we can use Jenkins to automatically issue the project version and SonarQube to test the code quality. In the access money, we need to package the project into a WAR package, which needs to be modified as follows:

1. Modify the project packaging type:

< the groupId > com. Jaycekon < / groupId > < artifactId > demo < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > <packaging>war</packaging>Copy the code

2, modify Application. Java file:

@SpringBootApplicationpublic class DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code

In my last blog, Doraemon portal, I explained some basic configuration methods, but here I will explain the configuration of accessing SonarQube for code quality inspection (requires A local installation of SonarQube service).

Add SonarQube’s project name to MetaData:

Then in Post Steps select Add Execute SonarQube Scanner:

After these two items are configured, Jenkins performs SonarQube code quality checks when the file is compiled.

Finally, we can set up the project after compiling, execute shell script, automatic release of the project:

After the project is compiled, we will find the Playbook under the project, execute the script inside, and deploy our project to the specified server.

The last

I have compiled a copy: Spring Boot related information, Mybatis related information documents, Spring family barrel series, Java systematic information, (including Java core knowledge, interview topics and 20 years of the latest Internet real questions, e-books, etc.) need friends can pay attention to the public number [procedure yuan small wan] can be obtained.