Java研究ノート-Day79Maven(3)



1つ、Swagger2

1.Swagger2の概要


swagger2は、RESTful Webサービスを生成、記述、呼び出し、および視覚化するための標準化された完全なフレームワークです。それは主に3つの部分で構成されています。

(1)swagger Codegen:Codegenを介して、記述ファイルをhtml形式およびcwiki形式のインターフェイスドキュメントに生成できます。また、多言語サーバーおよびクライアントコードを生成することもできます。

(2)swagger UI:視覚的なUIページ表示記述ファイルを提供します。一部のインターフェース要求を行うことができます。

(3)swagger Editor:swagger記述ファイルを編集するためのエディターで、記述ファイルの更新効果のリアルタイムプレビューをサポートします。オンラインエディターとローカルデプロイメントエディターには2つの方法もあります。

Swagger2はSpringに簡単に統合でき、SpringMVCプログラムと連携して強力なRESTfulAPIドキュメントを整理できます。ドキュメント作成の作業負荷を軽減するだけでなく、説明を実装コードに統合することで、ドキュメントのメンテナンスと変更したコードを統合し、コードを変更しながらドキュメントの説明を簡単に変更できるようにします。論理。さらに、Swagger2は、各RESTfulAPIをデバッグするための強力なページテスト機能も提供します。

2.実装手順


(1)3つのjarパッケージspringfox-swagger2、springfox-swagger-ui、bootstrapをプロジェクトにインポートします。つまり、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またはSpringMVCの設定ファイルにスキャンパスを追加します。すでに設定されている場合は、この手順を無視してかまいません。

  • 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アドレス:ページのドキュメントとテスト結果は次のとおりです。
ここに画像の説明を挿入

2、Redis

1.Redisの概要


Redisは完全にオープンソースであり、BSDプロトコルに準拠しています。これは、高性能のKey-Valueデータベース、メモリデータベース、およびNoSQLです。Redisは、Key-Valueなどの複数のデータ構造をサポートするストレージシステムです。キャッシュ、イベントの公開またはサブスクリプション、高速キューなどのシナリオで使用できます。データベースは、メモリに基づいてANSI C言語で記述されており、永続化でき、ネットワークをサポートし、文字列、ハッシュ、リスト、キュー、およびコレクション構造への直接アクセスを提供します。

Redisは、キーと5つの異なるデータ構造タイプの間のマッピングを格納できます。5つのデータ構造タイプは、文字列(文字列)、リスト(リスト)、セット(コレクション)、ハッシュ(ハッシュ)、およびZset(順序付き)です。

公式チュートリアルドキュメント:http://www.redis.net.cn/tutorial/3505.html

Redisのポート番号は6379です。

Redisのパフォーマンスは非常に高く、読み取り速度は110,000回/秒、書き込み速度は81,000回/秒です。

Redisは、頻繁に更新されず、頻繁に使用されるデータを保存するために使用できます。

2.Redisの機能


(1)Redisはデータの永続性をサポートしており、データをメモリからディスクに保存し、次回の起動後にメモリにロードできます。
(2)Redisは、単純なkey_valueタイプのデータだけでなく、list、set、hash、setなどの他の複雑なデータ構造もサポートします。
(3)Redisは、データバックアップ、つまりマスタースレーブモードでのデータバックアップをサポートしています。

3.SpringはRedisを統合します


キャッシング:同時実行性が高い場合、アクセスパフォーマンスを向上させるために、データベース内の頻繁に表示され、頻繁に変更されないデータの一部を、より高速なアクセスレートでメモリに保存する必要があります。これにより、データ取得時間が短縮され、エクスペリエンスが向上し、データベースへの負荷が軽減されます。キャッシュは、読み取りが多く、書き込みが少ない状況に適しています。クエリ中のキャッシュヒット率は非常に低く、書き込み操作は非常に少ないです。キャッシングはシナリオには適していません。

MySQLには独自のクエリキャッシュがありますが、Redisなどのキャッシュアプ​​リケーションを使用するのはなぜですか?MySQLサーバーが1つしかない場合は、キャッシュをローカルに配置できます。このようにして、同じSQLクエリが到着したときに、SQLの解析や実行を必要とせずに、クエリ結果をキャッシュから直接フェッチできます。MySQLはサーバーレベルのキャッシュサポートを提供します。MySQLサーバーが複数ある場合、リクエストは複数のサーバーの1つにランダムに分散されます。同じリクエストが同じサーバーに到達することは保証できず、ローカルキャッシュのヒット率は低くなります。したがって、このマシンに基づくキャッシュは無意味です。現時点で採用される戦略は、クエリ結果を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)リソースディレクトリの下に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-redis.xmlファイルをspring構成ファイルapplicationContext.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デスクトップマネージャーでRedisデータベースに保存されているデータを表示します。

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/qq_42141141/article/details/115038267