Java学习笔记-Day79 Maven(三)



一、Swagger2

1、Swagger2简介


swagger2 是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful 风格的Web 服务。它主要包含三部分:

(1)swagger Codegen:通过Codegen 可以将描述文件生成html格式和cwiki形式的接口文档,同时也能生成多钟语言的服务端和客户端的代码。

(2)swagger UI:提供了一个可视化的UI页面展示描述文件。可以做一些的接口请求。

(3)swagger Editor:编辑swagger描述文件的编辑器,该编辑支持实时预览描述文件的更新效果。也提供了在线编辑器和本地部署编辑器两种方式。

Swagger2可以轻松的整合到Spring中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。

2、实现步骤


(1)在项目中导入springfox-swagger2、springfox-swagger-ui、bootstrap三个jar包,即在Maven项目的pom.xml文件中添加如下代码:

<!--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)在项目src目录中创建com.etc.config包,并在该包中创建Swagger2的配置类。

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)加入扫描路径到Spring或者Spring MVC的配置文件中。如果已经设置,则可忽略此步。

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

(4)在类、方法、参数上添加对应的注解。

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)访问地址:http://localhost:8080/项目名/swagger-ui.html。页面文档和测试效果如下。
在这里插入图片描述

二、Redis

1、Redis简介


Redis 是完全开源的,遵守 BSD 协议,是一个高性能的 key-value 数据库、内存数据库、NoSQL。Redis是一种支持Key-Value等多种数据结构的存储系统。可用于缓存、事件发布或订阅、高速队列等场景。该数据库使用ANSI C语言编写,基于内存,可持久化,支持网络,提供字符串、哈希、列表、队列、集合结构直接存取。

Redis 可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。

官方教程文档:http://www.redis.net.cn/tutorial/3505.html

Redis 的端口号为 6379。

Redis 性能极高:读的速度是110000次/s、写的速度是81000次/s。

Redis 可以用于存储不经常更新和使用次数多的数据。

2、Redis的特点


(1)Redis支持数据的持久化,可以将内存中的数据存储到磁盘,下次启动后再加载到内存中。
(2)Redis支持不仅是简单的key_value类型的数据,value的值还可以是list、set、hash、set等其他复杂数据结构。
(3)Redis支持数据的备份,即master-slave模式的数据备份。

3、Spring整合Redis


缓存:在高并发下,为了提高访问的性能,需要将数据库中一些经常展现和不会频繁变更的数据,存放在存取速率更快的内存中。这样可以降低数据的获取时间,带来更好的体验减轻数据库的压力缓存适用于读多写少的场合,查询时缓存命中率很低、写操作很频繁等场景不适宜用缓存。

MySQL有自己的查询缓存,为什么还要使用 Redis 等缓存应用:当只有一台 MySQL服务器时,可以将缓存放置在本地。这样当有相同的 SQL 查询到达时,可以直接从缓存中取到查询结果,不需要进行 SQL 的解析和执行。MySQL 提供了服务器层面的缓存支持。如果有多台 MySQL 服务器,请求会随机分发给多台中的一台,我们无法保证相同的请求会到达同一台服务器,本地缓存命中率较低。所以基于本机的缓存就没有什么意义,此时采用的策略应该是将查询结果缓存在 Redis 或者 Memcache 中。而Redis是一个高性能的 key-value 内存数据库,可以作为缓存使用。

在 Java 中使用 Redis 开始之前,需要确保电脑上已经安装了 Redis 数据库,且能正常使用 Java。

使用步骤:
(1)在Maven项目的pom.xml文件中加入jedis、spring-data-redis的jar坐标。

<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)在resource目录下添加redis的配置文件 spring-redis.xml和redis.properties。

  • 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)在spring的配置文件applicationContext.xml文件中,导入spring-redis.xml文件,并加入redis.properties的关联。

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

(4)使用 redisTemplate 测试。

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 控制台输出结果:

在这里插入图片描述
在 Redis Desktop Manager 中查看Redis数据库中存储的数据:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42141141/article/details/115038267