1. 程式人生 > >Spring Boot整合JPA、Redis和Swagger2

Spring Boot整合JPA、Redis和Swagger2

enc code extends art redis學習 and 小結 JD pip

好久沒有總結了,最近也一直在學習。今天就把spring boot與其它技術的整合做個小總結,主要是jpa、redis和swagger2。公司裏有用到這些,整合起來也很簡單。

首先,新建一個Spring Boot 的項目,我這裏用的是之前一篇Spring Boot學習筆記---Spring Boot 基礎及使用idea搭建項目
是同一個項目。這裏我就不重新建項目了。

項目目錄

技術分享圖片

1.Spring Boot整合JPA

JPA我用的不是很多,但是在學習springboot和cloud的時候,都是用的jpa進行數據庫的操作,如果感覺興趣可以去學習一下。

1. 添加依賴

<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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
            <scope>runtime</scope>
        </dependency>

2.配置數據源

之前項目的配置文件是application.properties格式的,這裏我換成了application.yml格式的文件。作用是一樣的。

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/spring-cloud?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
        username: root
        password: 1111
      jpa:
        hibernate:
          ddl-auto: create #第一次建表 create 後面用update
        show-sql: true

3.創建實體對象,jpa根據註解自動建表

 package com.springboot.first.entity;

import javax.persistence.*;

/**
 * @Package main.java.com.jpa.jpastart.entity
 * @Description: 用戶
 * @auther MZ
 * @create 2018/5/30 21:11
 */
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false, unique = true)
    private String username;
    @Column
    private String password;
    //……省略
}

4.創建Dao層

package com.springboot.first.dao;


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

/**
 * 
 */
public interface UserDao extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

5.創建service層

package com.springboot.first.service;

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

import java.util.List;

/**
 * @Package main.java.com.jpa.jpastart.service
 * @Description: 用戶service
 * @auther MZ
 * @create 2018/5/30 21:21
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User findUserByName(String username) {
        return userDao.findByUsername(username);
    }

}

6.創建controller層

package com.springboot.first.controller;

import com.springboot.first.entity.User;
import com.springboot.first.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Package main.java.com.jpa.jpastart.controller
 * @Description: 控制器
 * @auther MZ
 * @create 2018/5/30 21:23
 */
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/{username}")
    public User getUser(@PathVariable("username") String username) {
        return userService.findUserByName(username);
    }

}

7.運行項目,查看結果,表建好後,可以插入幾條測試數據,方便查看。

技術分享圖片

技術分享圖片

2.Spring Boot整合Redis

關於redis的安裝,可以參考Redis學習-redis概述

1.添加依賴

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

2.添加配置信息

spring:
    redis:
        host: localhost
        port: 6379
        password:
        database: 1
        pool:
            max-active: 8
            max-wait: -1
            max-idle : 500   

3.添加RedisDao類,通過註解@Repository註入Spring IoC容器中。

package com.springboot.first.dao;

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;

/**
 * @Package com.springboot.first.dao
 * @Description: redis測試
 * @auther MZ
 * @create 2018/5/31 20:56
 */
@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);
    }

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

4.在FirstApplicationTests 添加測試方法

技術分享圖片

package com.springboot.first;

import com.springboot.first.dao.RedisDao;
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.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FirstApplicationTests {

    @Test
    public void contextLoads() {
    }
    @Autowired
    RedisDao redisDao;

    @Test
    public void testRedis(){
        redisDao.setKey("name","ma");
        redisDao.setKey("age","24");
        System.out.println(redisDao.getValue("name"));
        System.out.println(redisDao.getValue("age"));
    }
}

5.運行

技術分享圖片

3.Spring Boot整合Swagger2,搭建Restful Api在線文檔

Swagger是一個功能強大的在線API文檔的框架,公司整合用來開發對外接口。

1.添加依賴

<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,新建一個java類,做為配置類。

package com.springboot.first.config;

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;

/**
 * @Package com.springboot.first.config
 * @Description: swagger2配置
 * @auther MZ
 * @create 2018/6/1 21:12
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

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

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger構建api文檔")
                .description("學習使用")
                .termsOfServiceUrl("https://home.cnblogs.com/u/black-spike/")
                .version("1.0")
                .build();
    }
}

3.文檔註解

Swagger2通過註解來生成API接口文檔,文檔信息包括接口名、請求方法、參數、返回信息等。通常情況下生成的API文檔,以下接口可以滿足基本的需求:

  1. @Api:修飾整個類,用於描述Controller類。
  2. @ApiOperation:描述類的方法,或者說一個接口。
  3. @ApiParam:單個參數描述。
  4. @ApiModel:用於對象來接收參數。
  5. @ApiProperty:用對象接收參數時,描述對象的一個字段。
  6. @ApiResponse:HTTP響應一個描述。
  7. @ApiResponses:HTTP響應的整體描述
  8. @APiIgnore:使用該註解,表述Swagger2忽略這個API。
  9. @ApiError:發生錯誤返回的信息。
  10. @ApiParamImplicit:一個請求參數。
    11.@ApiParamsImplicit:多個請求參數。

4.在userservice中添加方法

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

5.在UserController中添加一個RESTful風格的API接口

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

6.運行,在頁面輸入http://localhost:8080/swagger-ui.html

技術分享圖片

小結

一直學習,但是都沒有好好的去總結。感覺這以後會用的到,到時候就方便一下了。

Spring Boot整合JPA、Redis和Swagger2