Java study notes-Day79 Maven (three)



One, Swagger2

1. Introduction to Swagger2


swagger2 is a standardized and complete framework for generating, describing, invoking, and visualizing RESTful Web services. It mainly consists of three parts:

(1) swagger Codegen: Through Codegen, description files can be generated in html format and cwiki format interface documents, and at the same time, server and client codes in multiple languages ​​can be generated.

(2) swagger UI: Provides a visual UI page display description file. Some interface requests can be made.

(3) swagger Editor: an editor for editing swagger description files, which supports real-time preview of the update effect of description files. There are also two ways of online editor and local deployment editor.

Swagger2 can be easily integrated into Spring, and cooperate with Spring MVC program to organize powerful RESTful API documents. It can not only reduce the workload of creating documents, but also integrate the description content into the implementation code, so that the maintenance document and the modified code are integrated into one, which allows us to modify the document description conveniently while modifying the code logic. In addition, Swagger2 also provides a powerful page testing function to debug each RESTful API.

2. Implementation steps


(1) Import the three jar packages springfox-swagger2, springfox-swagger-ui, bootstrap into the project, that is, add the following code to the pom.xml file of the Maven project:

<!--swagger2 jar start -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.1</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>bootstrap</artifactId>
	<version>3.3.5</version>
</dependency>
<!--swagger2 jar end -->

(2) Create the com.etc.config package in the project src directory, and create the configuration class of Swagger2 in the package.

package com.etc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableWebMvc
@EnableSwagger2
public class Swagger2 {
    
    
	// swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
	@Bean // 创建一个bean
	public Docket createRestApi() {
    
    
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				// 为当前包路径
				.apis(RequestHandlerSelectors.basePackage("com.etc.controller")).paths(PathSelectors.any()).build();
	}

	// 构建api文档的详细信息函数
	private ApiInfo apiInfo() {
    
    
		return new ApiInfoBuilder()
				// 页面标题
				.title("Spring测试使用 Swagger2 构建RESTful API")
				// 创建人
				.contact(new Contact("tom", "", ""))
				// 版本号
				.version("1.0")
				// 描述
				.description("API 描述").build();
	}
}

(3) Add the scan path to the configuration file of Spring or Spring MVC. If it is already set, you can ignore this step.

  • applicationContext.xml
	<!-- 扫描自动注入和bean有关的组件的包 -->
	<context:component-scan base-package="com.etc"></context:component-scan>

(4) Add corresponding annotations to classes, methods, and parameters.

package com.etc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.etc.entity.Book;
import com.etc.service.BookService;
import com.etc.util.AjaxResponse;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "图书接口", description = "图书控制器,实现了图书的检索,增加,修改等操作")
@Controller
public class TempController {
    
    
	@Autowired
	private BookService bookservice;

	@GetMapping("book/getlistbyname.do")
	@ApiOperation(value = "图书检索", notes = "实现图书名、简介、作者名、出版社名的模糊分页查询", httpMethod = "GET", response = AjaxResponse.class)
	@ResponseBody
	public AjaxResponse<Book> getBookList(
			@ApiParam(name = "booknamekeywords", required = false, value = "图书名") @RequestParam(value = "booknamekeywords", required = false, defaultValue = "") String booknamekeywords,
			@ApiParam(name = "introducekeywords", required = false, value = "简介") @RequestParam(value = "introducekeywords", required = false, defaultValue = "") String introducekeywords,
			@ApiParam(name = "authorkeywords", required = false, value = "作者名") @RequestParam(value = "authorkeywords", required = false, defaultValue = "") String authorkeywords,
			@ApiParam(name = "presskeywords", required = false, value = "出版社名") @RequestParam(value = "presskeywords", required = false, defaultValue = "") String presskeywords,
			@ApiParam(name = "bookbusinessid", required = false, value = "商家编号") @RequestParam(value = "bookbusinessid", required = false, defaultValue = "0") int bookbusinessid,
			@ApiParam(name = "page", required = false, value = "当前页数") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@ApiParam(name = "limit", required = false, value = "每页数量") @RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {
    
    
		//调用业务层方法实现分页查询
		PageInfo<Book> pageinfo = bookservice.showBookByPage(page, limit, booknamekeywords,introducekeywords,authorkeywords,presskeywords,bookbusinessid);
		//将返回结果转换为视图层能接受的数据格式,AjaxResponse=>Layui所以自己封装了一个对象
		AjaxResponse<Book> ar = new AjaxResponse<Book>(0, "success", (int) pageinfo.getTotal(), pageinfo.getList());
		return ar;
	}
	
}

(5) access http://localhost:8080/项目名/swagger-ui.htmladdress: . The page documentation and test results are as follows.
Insert picture description here

Two, Redis

1. Introduction to Redis


Redis is completely open source and complies with the BSD protocol. It is a high-performance key-value database, memory database, and NoSQL. Redis is a storage system that supports multiple data structures such as Key-Value. It can be used in scenarios such as caching, event publishing or subscription, and high-speed queues. The database is written in ANSI C language, based on memory, can be persisted, supports the network, and provides direct access to strings, hashes, lists, queues, and collection structures.

Redis can store the mapping between keys and five different data structure types. The five data structure types are String (string), List (list), Set (collection), Hash (hash) and Zset (ordered). set).

Official tutorial document:http://www.redis.net.cn/tutorial/3505.html

The port number of Redis is 6379.

Redis has extremely high performance: the read speed is 110,000 times/s, and the write speed is 81,000 times/s.

Redis can be used to store data that is not frequently updated and frequently used.

2. Features of Redis


(1) Redis supports data persistence, which can store data in memory to disk and load it into memory after the next startup.
(2) Redis supports not only simple key_value data, but also other complex data structures such as list, set, hash, and set.
(3) Redis supports data backup, that is, data backup in master-slave mode.

3. Spring integrates Redis


Caching : Under high concurrency, in order to improve access performance, some frequently displayed and infrequently changed data in the database needs to be stored in a memory with a faster access rate. This can reduce the data acquisition time, bring a better experience and reduce the pressure on the database. Cache is suitable for situations where there are more reads and less writes. The cache hit rate is very low during query, and the write operation is very frequent. Caching is not suitable for scenarios.

MySQL has its own query cache, why use caching applications such as Redis ? When there is only one MySQL server, the cache can be placed locally. In this way, when the same SQL query arrives, the query result can be directly fetched from the cache, without the need for SQL parsing and execution. MySQL provides server-level caching support. If there are multiple MySQL servers, the request will be randomly distributed to one of the multiple MySQL servers. We cannot guarantee that the same request will reach the same server, and the local cache hit rate is low. Therefore, caching based on this machine is meaningless. At this time, the strategy adopted should be to cache the query results in Redis or Memcache. Redis is a high-performance key-value memory database that can be used as a cache.

Before using Redis in Java, you need to make sure that the Redis database has been installed on your computer and Java can be used normally.

Use steps:
(1) Add the jar coordinates of jedis and spring-data-redis in the pom.xml file of the Maven project.

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>3.1.0</version>
</dependency>
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-redis</artifactId>
	<version>2.3.3.RELEASE</version>
</dependency>

(2) Add the redis configuration files spring-redis.xml and redis.properties under the resource directory.

  • spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
	<!-- 配置JedisPoolConfig相关参数 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxWaitMillis" value="${redis.maxWait}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>
	
	<!-- redis服务器中心 -->
	<bean id="jedisconnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="poolConfig" ref="poolConfig" />
		<property name="port" value="${redis.port}" />
		<property name="hostName" value="${redis.host}" />
		<property name="password" value="${redis.password}" />
		<property name="timeout" value="${redis.timeout}"></property>
	</bean>
	
	<!-- value序列化 -->
	<bean id="genericJackson2JsonRedisSerializer"
		class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
	<!-- key 序列化 -->
	<bean id="stringRedisSerializer"
		class="org.springframework.data.redis.serializer.StringRedisSerializer" />
	
	<!-- redisTemplate 的配置 -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<!-- 注入 connectionFactory -->
		<property name="connectionFactory" ref="jedisconnectionFactory" />
		<!-- stringRedisSerializer -->
		<property name="keySerializer" ref="stringRedisSerializer" />
		<!-- valueSerializer -->
		<property name="valueSerializer" ref="genericJackson2JsonRedisSerializer" />
	</bean>
</beans>
  • redis.properties
redis.port=6379
redis.host=127.0.0.1
redis.password=
redis.timeout=100000
redis.maxIdle=100
redis.maxWait=1000
redis.maxActive=300
redis.testOnBorrow=true

(3) Import the spring-redis.xml file in the spring configuration file applicationContext.xml file, and add the association of redis.properties.

<context:property-placeholder location="classpath:redis.properties" />
<import resource="spring-redis.xml"/>

(4) Use redisTemplate to test.

package com.etc.test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.context.web.WebAppConfiguration;

@SpringJUnitConfig(locations = "classpath:applicationContext.xml")
@WebAppConfiguration
public class TestRedisTemplate {
    
    

	@Autowired
	RedisTemplate redisTemplate;

	@Test
	public void test1() {
    
    
		// 存储数据
		redisTemplate.opsForValue().set("spring", "spring-redis");
		// 获取数据
		System.out.println(redisTemplate.opsForValue().get("spring"));
	}
}

Eclipse console output:

Insert picture description here
View the data stored in the Redis database in Redis Desktop Manager:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42141141/article/details/115038267