Spring Could-01-開發框架Spring Boot

1. Spring Boot 簡介

       Spring Boot框架提供了自動裝配和起步依賴,是開發人員不需要配置各種配置文件(比如xml文件),這種方式極大的地提高了程序的開發速度,因此,Spring Boot框架已經成爲新一代的Java Web開發框架。
       Spring Boot不僅提供了自動裝配、起步依賴,還自帶了不少非功能性的特性,例如安全、度量、健康檢查、內嵌Servlet容器和外置配置。開發人員可以更加敏捷快速地開發Spring程序,專注於應用程序本身的業務開發,而不是在Spring的配置上花費大量的精力。
       另外,Actuator提供了運行時的Spring Boor程序中的監控端點,讓開發人員和運維人員實時瞭解程序的運行情況。

2. 用IDEA構建Spring Boot工程

源碼:

鏈接:https://pan.baidu.com/s/1ipssal8N5n9nPM-W1Wsmuw 
提取碼:p42m

打開"IDEA"→"new Project"→"Spring Initializr"→填寫"group"和"artifact"→勾選"web"(開啓web功能)→單擊"下一步"。IDEA會自動下載Spring Boot工程的模板。

2.1 項目結構

創建完工程後,工程的目錄結構如下:
在這裏插入圖片描述
各目錄的含義如下:

  • pom文件爲依賴管理文件
  • resources爲資源文件夾
  • stastic爲靜態資源
  • templates爲模板資源
  • application.yml爲配置文件
  • SpringCouldSpringBootApplication.java爲程序的啓動類

2.2 在 Spring Boot工程中構建Web程序

spring-boot-starter-web爲Web功能的起步依賴,它會自動導入與Web相關的依賴。spring-boot-starter-test爲Spring Boot測試功能的起步依賴,它會導入與Spring Boot測試相關的依賴,代碼如下:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
     <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

在工程的主目錄下有一個SpringCouldSpringBootApplication.java類,該類爲程序的啓動類,代碼如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringCloudSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudSpringBootApplication.class, args);
    }

}

其中,
@SpringBootApplication註解包含了@SpringBootConfiguration、@EnableAuto-Configuration和@ComponentScan,開啓了包掃描、配置和自動配置的功能。
創建一個Web層的Controller,代碼如下:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String index(){
        return "歡迎來到SpringBoot";
    }
}

啓動SpringCloudSpringBootApplication裏面的main方法
訪問: http://localhost:8080/hello
在這裏插入圖片描述
其中,
@RestController註解表明這個類是一個RestController。@RestController是Spring4.0版本的一個註解,它的功能相當於@Controller註解和@ResponseBody註解之和。
@RequestMapping註解是配置請求地址的Url映射的。

2.3 Spring Boot的測試

Spring Boot 開啓測試也非常簡單,只需要加@RunWith(SpringRunner.class)和@SpringBootTest註解,在@SpringBootTest註解上加上web測試環境的端口爲隨機端口的配置。TestRestTemplate類爲RestTemplate測試類,RestTemplate用於遠程調用Http API接口。
需要添加依賴

<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @RunWith(SpringRunner.class) 和 @SpringBootTest 即可開啓spring boot測試
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/hello");
    }

    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(),
                String.class);
        assertThat(response.getBody(), equalTo("歡迎來到SpringBoot"));
    }
}

3. Spring Boot配置文件詳解

3.1 自定義屬性

在配置文件application.yml自定義一組屬性,如下:

my:
  name: wyc
  age: 27

如果要讀取配置文件application.yml的屬性值,只需要在變量上加@Value("${屬性名}")註解,就可以將配置文件的一個屬性值賦給一個變量。新建一個Controller:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MiyaContaoller {

    @Value("${my.name}")
    private String name;
    @Value("${my.age}")
    private String age;

    @RequestMapping("/miya")
    public String miya(){
        return name + ":" + age;
    }
}

啓動工程,訪問 http://localhost:8080/miya
在這裏插入圖片描述

3.2 將配置文件中的屬性賦給實體類

當有很多配置屬性的時候,如果諸葛讀取會非常麻煩,通常的做法就是把這些屬性作爲變量名來創建一個JavaBean的變量,並將屬性的值賦給JavaBean變量的值。
在配置文件application.yml中添加如下屬性:

my:
  name: wyc
  age: 27
  number: ${random.int}
  uuid: ${random.uuid}
  max: ${random.int(10)}
  value: ${random.value}
  greeting: hi,i'm ${my.name}

${random}:可以用來生成各種不同類型的隨機值
random.int:隨機生成一個int類型 的值
random.uuid:隨機生成一個uuid
random.value:隨機生成一個值
random.int(10):隨機生成一個小於10的整數
創建一個JavaBean:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "my")
@Component
public class ConfigBean {
    private String name;
    private int age;
    private int number;
    private String uuid;
    private int max;
    private String value;
    private String greeting;
    // getter,setter...
}    

在ConfigBean 類上加一個註解@ConfigurationProperties,表明該類是一個配置屬性類,並加上配置的prefix,例如本案例的"my",另外需要在ConfigBean 類上加@Component註解,Spring Boot啓動時通過包掃描將該類作爲一個Bean注入IOC容器中。
創建一個Controller,讀取ConfigBean類的屬性,在Controller類上,加@EnableConfigurationProperties註解,並制定ConfigBean類:

import com.wyc.bean.ConfigBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by : wyc
 * Created time 2020/6/19 7:18
 */
@RestController
@EnableConfigurationProperties({ConfigBean.class})
public class LucyController {

    @Autowired
    ConfigBean configBean;
    
    @RequestMapping(value = "/lucy")
    public String lucy(){
        return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax();
    }

}

啓動訪問http://localhost:8080/lucy
在這裏插入圖片描述

3.3 自定義配置文件

上面是將配置屬性寫到application.yml中,並把配置屬性讀取到一個配置類中。如果配置屬性太多時,我們可以自定義配置文件.例如在src/main/rasources目錄下自定義一個test.properties配置文件:

com.forezp.name=forezp
com.forezp.age=12

將test.properties的屬性和屬性值賦值給一個JavaBean,需要在類名上加@Configuration,@PropertySource,@ConfigurationProperties這三個註解.需要注意的是若Spring Boot版本爲1.4或1.4之前,則需要在@PropertySource註解上加location,並指明改配置文件的路徑.本案例採用的是Spring Boot版本爲2.1.0:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.forezp")
public class User {
    private String name;
    private int age;
    //getter,setter...
}

創建一個Controller,在類上加上@RestController,和@EnableConfigurationProperties,並指明需要引用的JavaBean的類,開啓引用配置屬性的功能:

import com.wyc.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableConfigurationProperties({User.class})  //多個Bean可以用,隔開
public class LucyController {
    @Autowired
    private User user;
    @RequestMapping( "/user")
    public String user(){
        return user.getName()+user.getAge();
    }
}

啓動訪問: http://localhost:8080/user
在這裏插入圖片描述

3.4 多個環境的配置文件

在實際開發中,可能有多個不同環境的配置文件,Spring Boot支持程序啓動時在配置文件application.yml中指定環境的配置文件,配置文件的格式爲application-{profile}.properties(yml),其中{profile}對應環境的標識:

  • application-test.properties(yml) -----測試環境
  • application-dev.properties(yml) -----開發環境
  • application-uat.properties(yml) -----預發環境
  • application-prod.properties(yml) -----生產環境
    使用選擇環境的配置文件的時候,只需要在application.yml上加上spring.profiles.active的配置,該配置指定採用哪一個profiles,例如使用application-dev.properties(yml),則配置文件代碼如下:
#多個環境的配置文件切換
# active=dev 讀取application-dev.yml配置文件
# active=pro 讀取application-pro.yml配置文件
spring:
  profiles:
    active: dev

application-dev.yml配置文件中指定程序的啓動端口:

server:
  port: 8082

啓動工程,訪問端口就變成了8082了.
還可以通過java -jar的方式啓動程序,並指定程序的配置文件:

java -jar spring-boot.jar -- spring.profiles.active=dev

4. 運行狀態監控Actuator

Spring Boot的Actuator提供了運行狀態的監控功能,Actuator的監控數據可以通過REST、遠程shell(1.5後的版本棄用)和JMX方式獲得.
REST方式查看Actuator的結點的方法是最常見切簡單的方法。
在工程pom中引入Actuator的起步依賴spring-boot-starter-actuator:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

在配置文件application.yml中配置management.port和management.security.enabled,這兩個配置分別配置了Actuator對外暴露REST API接口的端口號和Actuator採取非安全驗證方式:

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS
    shutdown:
      enabled: true # 必須將此屬性設置爲true 才能執行 curl -X POST http://localhost:9001/actuator/shutdown 命令
  server:
    port: 9001 # 指定Actuator對外暴露的REST API接口端口爲9001

上述代碼中指定了Actuator對外暴露的REST API接口的端口號爲9001,如果不指定,端口號爲應用程序的啓動端口,這樣做的目的是將程序端口可程序的監控端口分開.將配置management.endpoints.web.exposure.include設置爲"*",暴露Actuator組件的所有節點,將配置management.endpoint.shutdown.enabled設置爲"true",開啓可以通過請求來關閉程序的功能.啓動工程,在控制檯可以看到如下信息:
在這裏插入圖片描述
由上信息可知,Spring Boot的Actuator開啓了14個節點,並且Actuator的監控端口爲9001,應用程序的端口爲8082.
Actuator提供了13個API接口,用於監控運行狀態的Spring Boot的狀況.需要注意的是,API接口需要加上"/actuator"前綴才能訪問.
                                              Actuator端口信息

類型 API端口 描述
GET /autoconfig 提供了一份自動配置報告,記錄哪些自動配置條件通過了,哪些沒有通過
GET /configprops 描述配置屬性如何注入Bean
GET /beans 描述應用程序上下文裏全部的bean,以及他們的關係
GET /threaddump 獲取線程活動的快照
GET /env 獲取全部環境屬性
GET /sessions 用戶會話
GET /health 應用程序的健康指標
GET /info 獲取應用程序的信息
GET /auditevents 顯示當前應用程序的審計事件信息
GET /conditions 顯示配置類和自動配置類的狀態,以及它們被應用或被應用的原因
GET /flyway 顯示數據庫遷移路徑
GET /liquibase 顯示任何Liquibase數據遷移路徑(如果存在)
GET /loggers 顯示和設置Logger的級別
GET /mappings 描述全部的URI路徑,以及它們的控制器(包含Actuator端點)的映射關係
GET /metrics 獲取應用程序度量信息,例如內存用量和HTTP請求計數
GET /scheduledtasks 顯示應用程序中的計劃任務
POST /shutdown 關閉應用程序,需要將endpoints.shutdown.enabled設置爲true
GET /httptrace 提供基本的HTTP請求跟蹤信息(時間戳、HTTP頭等)
GET /caches 暴露可用緩存

4.1 查看運行程序的健康狀態

訪問 http://localhost:9001/actuator/health

{
	"status": "UP",
	"components": {
		"diskSpace": {
			"status": "UP",
			"details": {
				"total": 314572795904,
				"free": 300197081088,
				"threshold": 10485760,
				"exists": true
			}
		},
		"ping": {
			"status": "UP"
		}
	}
}

                  Spring Boot 自帶的健康指示器

指示器 內容
ApplicationHealthIndicator none 永遠爲UP
DataSourceHealthIndicator db 如果數據庫能連上則爲UP;否則爲DOWN
DiskSpaceHealthIndicator diskSpace 如果可用空間大於閾值,則爲UP和可用磁盤空間;如果空間不足,則爲DOWN
JmsHealthIndicator jms 如果能連上消息代理,則爲UP;否則爲DOWN
MailHealthIndicator mail 如果能連上郵件服務器,則爲UP和郵件服務器主機和端口;否則爲DOWN
MongoHealthIndicator mongo 如果能連上MongoDB服務器,則爲UP和MongoDB服務器版本;否則爲DOWN
RabbitHealthIndicator rabbit 如果能連上RabbitMQ服務器,則爲UP和版本號;否則爲DOWN
RedisHealthIndicator redis 如果能連上服務器,則爲UP和Redis服務器版本:否則爲DOWN
SolorHealthIndicator solr 如果能連上Solr服務器,則爲UP:否則爲DOWN

4.2 查詢運行程序的Bean

如果需要連接Spring Boot上下文注入了哪些Bean,這些Bean的類型,狀態,生命週期德國信息時,只需要發起一個GET類型的請求,請求API爲"/bean",訪問:
http://localhost:9001/actuator/beans

{
	"contexts": {
		"application": {
			"beans": {
				"endpointCachingOperationInvokerAdvisor": {
					"aliases": [],
					"scope": "singleton",
					"type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
					"resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
					"dependencies": [
						"environment"
					]
				},
				"defaultServletHandlerMapping": {
					"aliases": [],
					"scope": "singleton",
					"type": "org.springframework.web.servlet.HandlerMapping",
					"resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]",
					"dependencies": []
				},
				"metricsRestTemplateCustomizer": {
					"aliases": [],
					"scope": "singleton",
					"type": "org.springframework.boot.actuate.metrics.web.client.MetricsRestTemplateCustomizer",
					"resource": "class path resource [org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfiguration.class]",
					"dependencies": [
						"simpleMeterRegistry",
						"restTemplateExchangeTagsProvider",
						"management.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties"
					]
				},
		
			..............
			..............
			"parentId": null
		}
	}
}
  • beans :Spring 應用程序上下文中的Bean名稱或Id
  • resources :class文件的物理位置,通常是一個Url,指向構建出的Jar文件的路徑
  • scope :Bean的作用域(通常是單例singleton,也可以是ptototype,request和session)
  • type :Bean的類型

4.3 使用Actuator關閉應用程序

當需要關閉某個應用程序的時候,只需要通過Actuator發送一個POST請求"/shutdown".很顯然,關閉程序是一個非常危險的事,所以默認的情況下應用程序的API接口沒有開啓的.通過Crul模擬關閉應用程序的請求,Curl命令如下:

curl -X POST http://localhost:9001/actuator/shutdown

在這裏插入圖片描述
如果得到的響應信息爲:

{
	"timestamp": 1425364758687,
	"status": 404,
	"error": "Not Found",
	"message": "No message available",
	"path": "/shutdown"
}

原因:需要將endpoints.shutdown.enabled改爲true,在application.yml中添加:

management:
  endpoint:
    shutdown:
      enabled: true # 必須將此屬性設置爲true 才能執行 curl -X POST http://localhost:9001/actuator/shutdown 命令

然後請求

5. Spring Boot整合JPA

源碼:

鏈接:https://pan.baidu.com/s/1kPzs0RNo-p9SGcdQc3PTxQ 
提取碼:wics

JPA是一個數據持久化框架,目前在Java項目開發中提到JPA一般是通過Hibernate的實實現,因爲在Java的ORM框架中,只有hibernate實現的最好.
(1) 新建一個Spring Boot項目
pom.xml中引入依賴

<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-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

(2) 配置數據源
需要配置兩個選項:DataSource數據源的配置和JPA的配置.
數據源的配置:

  • 連接MySQL的驅動類(com.mysql.jdbc.Driver)
  • MySQL數據庫的地址Url
  • MySQL數據庫的用戶名和密碼
    JPA的配置
  • hibernate.ddl-auto :配置爲create時,程序啓動時,會在MySQL數據庫中建表;配置爲update時,在程序啓動時不會在MySQL數據庫中建表
  • jpa.show-sql : 該配置爲在通過JPA操作數據庫時是否顯示操作的SQL語句,
# 配置數據源
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/spring_cloud?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&serverTimezone=GMT%2B8
    username: root
    password: 123456

  jpa:
    hibernate:
      ddl-auto: create  # 第一次建表create  後面用update
    show-sql: true # 該配置爲在通過JPA操作數據庫時是否顯示操作的SQL語句

(3) 創建實體對象
@Entity : 註解表明該類是一個實體類,它和數據庫的表名相對應;
@Id : 註解表明該變量對應於數據庫中的Id, @GeneratedValue : 註解配置I d 字段爲自增長;@Column : 表明該變量對應於數據庫表中的字段, unique = true : 表明該變量對應於數據庫表中的字段爲唯一約束

import javax.persistence.*;

@Entity
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(nullable = false,  unique = true)
	private String username;

	@Column
	private String password;
	//getter,setter.........
}

(4) 創建DAO層
數據訪問層,編寫DAO類繼承JapanRepository的接口,繼承之後就能對數據庫進行讀寫操作,包含了基本的單表查詢的方法.

import com.wyc.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;


public interface UserDao extends JpaRepository<User, Long> {

	User findByUsername(String username);
}

(5) 創建Service層

import com.wyc.dao.UserDao;
import com.wyc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired
    private UserDao userDao;
    
    public User findByUsername(String userName){
        return this.userDao.findByUsername(userName);
    }
}

(6) 創建Controller層
寫一個GET類型的API接口,@PathVariable註解可以獲取RESTful風格的Url路徑上面的參數.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootJpaApplication {

    public static void main(String[] args) {

        SpringApplication.run(SpringBootJpaApplication.class,args);
    }
}

啓動服務會發現會在數據庫中插入一張user表
向數據庫插入一條數據

INSERT INTO `user`(`id`, `password`, `username`) VALUES (1, '123456', 'wyc');

訪問 http://localhost:8080/user/findByUsername/wyc
在這裏插入圖片描述

6. Spring Boot整合Redis

6.1 Redis簡介

        Redis是一個開源的,先進的key-value存儲系統,可用於構建高性能額存儲系統.Redis支持數據結構有字符串,哈希,列表,集合,排序集合,位圖,超文本等.NoSQL(Not Only SQL)泛指非關係型的是數據庫.Redis是一種NoSQL,Redis具有很多的有點,例如讀寫非常快速,支持豐富的數據類型,所有的操作都是原子的.

6.2 Redis的安裝

https://github.com/MSOpenTech/redis/releases 下載ZIP版本,解壓運行redis-server.exe即可在這裏插入圖片描述
在這裏插入圖片描述

6.3 在Spring Boot中使用Redis

源碼:

鏈接:https://pan.baidu.com/s/1MIrlYY6lWh8s1FTd90dPHQ 
提取碼:yl1f

創建工程在pom.xml中引入依賴

  <!--Redis起步依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

在工程的配置文件application.yml中加上Redis的數據源配置,如果Redis設置了密碼,需要提供密碼,選擇序號爲1的數據庫,配置Pool的相關配置:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 1
    jedis:
      pool:
        max-active: 8
        max-wait: 1
        max-idle: 500
        min-idle: 0
    timeout: 200

數據操作層的RedisDao類通過@Repository註解來注入Spring IOC容器中,各類是通過RedisTemplate類來訪問Redis的,通過注入StringRedisTemplate的Bean來對Redis數據庫中的字符串類型的數據進行操作:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 *
 *數據操作層的RedisDao 類通過@Repository 註解來注入Spring IoC 容器中, 該類是通過RedisTemplate 來訪問Redis的。
 * 通過注入StringRedisTemplate 的Bean 來對Redis 數據庫中的字符串類型的數據進行操作, 寫了兩個方法,
 * 包括向Redis 中設置String 類型的數據和從Redis中讀取String 類型的數據。
 */
@Repository
public class RedisDao {

    @Autowired
    private StringRedisTemplate template;

    public  void setKey(String key,String value){
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key,value,1, TimeUnit.MINUTES);//1分鐘過期
    }

    public String getValue(String key){
        ValueOperations<String, String> ops = this.template.opsForValue();
        return ops.get(key);
    }
}

在SpringBootTest 的測試類中注入RedisDao , 首先通過RedisDao 向Redis 設置兩組字符串值, 即name 爲wyc,age 爲27 的兩組字符串,然後分別通過RedisDao 從Red is 中讀取這兩個值,並打印山來:

import com.wyc.dao.RedisDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by : wyc
 * Created time 2020/6/21 22:45
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTest {
    public static Logger logger= LoggerFactory.getLogger(SpringBootRedisApplicationTest.class);
    @Autowired
    private RedisDao redisDao;

    @Test
    public void testRedis(){
        redisDao.setKey("name","wyc");
        redisDao.setKey("age","27");
        logger.info(redisDao.getValue("name"));
        logger.info(redisDao.getValue("age"));
    }
}

7. Spring Boot整合Swagger2,搭建Restful API在線文檔

源碼:

鏈接:https://pan.baidu.com/s/1wlbizxBa1VCLzn7QgF4O-w 
提取碼:7sge

Swagger是一個功能強大的在線API文檔的框架.Swagger2提供了在線文檔的查閱和測試功能,利用Swagger2很容易構建ReESTful風格的API
(1) pom.xml中引入依賴

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

(2) 配置swagger2
寫一個配置類Swagger,在類上加上@Configuration註解,表明是一個配置類,加上@EnableSwagger2開啓Swagger2的功能,
在配置類Swagger2 中需要注入一個Docket 的Bean , Bean 包含了apiInfo ,即基本API 文檔的描述信息,以及包掃描的基本包名等信息:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * Created by : wyc
 * Created time 2020/6/22 6:43
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.wyc.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("springBoot利用swagger構建api文檔")
                .description("簡單優雅restful風格")
//                .termsOfServiceUrl("/")
                .version("1.0")
                .build();
    }
}

(3) 寫生成文檔的註解
Swagger2通過註解來生成API接口文檔,文檔信息包括接口名,請求方法,參數,返回信息等.通常情況下用於生成在線API文檔,以下的註解能夠滿足基本需求:

  • @Api : 修飾整個類,用於描述Controller 類。
  • @ApiOperation :描述類的方法,或者說一個接口。
  • @ApiParam : 單個參數描述。
  • @ApiModel :用對象來接收參數。
  • @ApiProperty :用對象接收參數時,描述對象的一個字段。
  • @ApiResponse : HTTP 響應的一個描述。
  • @ApiResponses : HTTP 響應的整體描述。
  • @Apilgnore :使用該註解,表示Swagger2 忽略這個API 。
  • @ApiError : 發生錯誤返回的信息。
  • @ApiParamlmplicit : 一個請求參數。
  • @ApiParamsimplicit : 多個請求參數。
    (4) 實體類
import javax.persistence.*;


@Entity
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(nullable = false,  unique = true)
	private String username;

	@Column
	private String password;
//getter,setter.......
}

(5) DAO層

import com.wyc.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;


public interface UserDao extends JpaRepository<User, Long> {

	User findByUsername(String username);
}

(6) service層

/**
 * Created by : wyc
 * Created time 2020/6/21 9:30
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public User findByUsername(String userName){
        return this.userDao.findByUsername(userName);
    }

    public List<User> findAll(){
        return userDao.findAll();
    }

    public User saveUser(User user){
        return  userDao.save(user);
    }

    public Optional<User> findUserById(Long id){
        return userDao.findById(id);
    }
    public User updateUser(User user){
        return userDao.saveAndFlush(user);
    }
    public void deleteUser(Long id){
        userDao.deleteById(id);
    }
}

(7)Web層

在Web層通過Get,Post,Delete,Put這4中http方法,構建一組以資源爲中心的Restful風格的Api接口:

import com.wyc.entity.User;
import com.wyc.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Optional;

/**
 * Created by : wyc
 * Created time 2020/6/21 9:34
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findByUsername/{userName}")
    public User findByUsername(@PathVariable("userName") String userName){
        return this.userService.findByUsername(userName);
    }

    @ApiOperation(value = "用戶列表", notes = "用戶列表")
    @RequestMapping(value = "/getUsers",method = RequestMethod.GET)
    public List<User> getUsers(){
        List<User> users = this.userService.findAll();
        return users;
    }

    @ApiOperation(value = "創建用戶", notes = "創建用戶")
    @RequestMapping(value = "/postUser",method = RequestMethod.POST)
    public User postUser(@RequestBody User user){
        return this.userService.saveUser(user);
    }

    @ApiOperation(value="獲用戶細信息", notes="根據url的id來獲取詳細信息")
    @RequestMapping(value="/getUser/{id}", method= RequestMethod.GET)
    public Optional<User> getUser(@PathVariable Long id) {
        return this.userService.findUserById(id);
    }

    @ApiOperation(value="更新信息", notes="根據url的id來指定更新用戶信息")
    @RequestMapping(value="/putUser/{id}", method= RequestMethod.PUT)
    public User putUser(@PathVariable Long id, @RequestBody User user) {
        User user1 = new User();
        user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setId(id);
        return this.userService.updateUser(user1);

    }
    @ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除用戶")
    @RequestMapping(value="/deleteUser/{id}", method= RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        this.userService.deleteUser(id);
        return "success";
    }

    @ApiIgnore//使用該註解忽略這個API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }
}

通過@ApiOperation註解描述生成在線文檔的具體API說明,其中value值爲改接口的名稱,notes值爲接口的詳細文檔說明,這樣就可以讓Swagger2生成在線的APi接口文檔了.如果不需要某接口文檔,只需要加@ApiIgnore註解即可.
啓動工程訪問: http://localhost:8080/swagger-ui.html#/user-controller
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章