SpringBoot架構用了這麼久了,今天就來總結一下
SpringBoot的優點和特性這裡就不說了,我今天要結合Redis和MyBatis和Lombook來搭建一個簡單的SpringBoot架構。
首先我們從建立一個SpringBoot項目開始,當然,我用的項目管理工具是maven
版本資訊:
SpringBoot > 2.0.3
Maven > 3.5.3
JDK > 1.8
上圖是剛建立好的SpringBoot項目的初始結構
接下來需要将項目所需的包配置在pom.xml檔案中:
文中已加了詳細的注解:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>GnayEyTestProject</artifactId>
<version>0.0.1-GnayEy</version>
<packaging>jar</packaging>
<name>GnayEyTestProject</name>
<description>GnayEyTestProject project for Spring Boot</description>
<!-- SpringBoot版本,當然你也可以使用最新的版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from service -->
</parent>
<!-- UTF8編碼格式 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 這裡配置的是lombook,你的開發工具也需要配置lombok,這點可以上百度查 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.20</version>
</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-tomcat</artifactId>
</dependency>
<!-- 在沒有前台之前,項目使用swagger來進行接口的調試 -->
<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>
<!-- mybatis配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--jdbc連接配接池配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!-- redis操作需導入包 -->
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
</dependency>
<!-- 我加了一個Excel檔案的讀取功能,需要此配置:字尾為xlsx或xls的excel操作需要導入包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
</repositories>
</project>
pom.xml檔案配置文成後,右鍵項目,店家maven–Update Project…,項目會自動下載下傳所配置的jar包。
完成後,需要先準備一些工具類:
redis操作類:如圖是目錄結構
這三個類是操作redis的工具類。
下面貼上代碼:
package com.gnayey.common.staticconf;
//用來從配置檔案擷取redis的連結資訊
public class SystemStartupValue {
public static String REDIS_IP;
public static Integer REDIS_PORT;
}
package com.gnayey.redis;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import com.gnayey.common.staticconf.SystemStartupValue;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisPoolUtil {
private static volatile JedisPool jedisPool = null;
private JedisPoolUtil() {
}
public static JedisPool getJedisPoolInstance() {
if(jedisPool == null) {
synchronized (JedisPoolUtil.class) {
if(jedisPool == null) {
Configuration conf = null;
try {
conf = new PropertiesConfiguration("config.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(conf.getInt("maxIdle"));
config.setMaxWaitMillis(conf.getInt("maxWaitMillis"));
config.setTestOnBorrow(conf.getBoolean("testOnBorrow"));
config.setMaxTotal(conf.getInt("maxTotal"));
if(SystemStartupValue.REDIS_IP!=null && SystemStartupValue.REDIS_PORT!=0){
jedisPool = new JedisPool(config, SystemStartupValue.REDIS_IP, SystemStartupValue.REDIS_PORT);
}else{
jedisPool = new JedisPool(config, conf.getString("host"), conf.getInt("port"));
}
}
}
}
return jedisPool;
}
public static void release(JedisPool jedisPool, Jedis jedis) {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
RedisClient 類的内容為操作redis的具體方法,也可以添加方法來滿足自己的業務
package com.gnayey.redis;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import org.apache.commons.configuration.ConfigurationException;
public class RedisClient {
private Jedis jedis;// 非切片額用戶端連接配接
private JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance(); //非切片資料庫連接配接池
public RedisClient() {
synchronized (this) {
if(jedis == null) {
jedis = jedisPool.getResource();
}
}
}
/**
* 關閉資源
*/
public void closeResource(){
if(jedis != null) {
try {
JedisPoolUtil.release(jedisPool, jedis);
} catch (Exception e) {
}
}
}
/**
* 用于key-value形式擷取值
* @param key
* @return
*/
public String getValue(String key) {
String str = jedis.get(key);
return str;
}
/**
* 擷取List全部集合
* @param key
* @return
*/
public List<String> getList(String key) {
List<String> list = jedis.lrange(key, 0, -1);
return list;
}
/**
* 擷取List集合中一部分,start:開始下标(list從0開始計數),end:結束下标(填寫-1表示擷取全部list)
* @param key
* @param start
* @param end
* @return
*/
public List<String> getList(String key, int start, int end) {
List<String> list = jedis.lrange(key, start, end);
return list;
}
/**
* 擷取指定下标的list資料
* @param key
* @param index
* @return
*/
public String getListByIndex(String key, int index) {
String str = jedis.lindex(key, index);
return str;
}
/**
* 擷取Set全部集合
* @param key
* @return
*/
public Set<String> getSet(String key) {
Set<String> set = jedis.smembers(key);
return set;
}
/**
* 檢查content是否存在于key集合中
* @param key
* @param content
* @return
*/
public boolean isInSet(String key, String content) {
boolean bool = jedis.sismember(key, content);
return bool;
}
/**
* 擷取hash表中value集合
* @param key
* @return
*/
public List<String> getHashVal(String key){
List<String> list = jedis.hvals(key);
return list;
}
/**
* 判斷conent是否在key的hash中時候存在
* @param key
* @param content
* @return
*/
public boolean isInHash(String key, String content){
boolean bool = jedis.hexists(key, content);
return bool;
}
/**
* 擷取hash中字段為contents1,contents2...的值
* @param key
* @param contents
* @return
*/
public List<String> getHash(String key,String ... contents){
List<String> list = jedis.hmget(key, contents);
return list;
}
/**
* 擷取hash為key的某一字段
* @param key
* @param content
* @return
*/
public String getHashVal(String key, String content) {
String str = jedis.hget(key, content);
return str;
}
/**
* 擷取hash中所有的key
* @param key
* @return
*/
public Set<String> getHashKeys(String key){
Set<String> set = jedis.hkeys(key);
return set;
}
/**
* 擷取hash中所有的key
* @param key
* @return
*/
public Set<String> getKeys(String key){
Set<String> set = jedis.keys(key);
return set;
}
/**
* 擷取指定hash表中指定字段的value
* @param key
* @param field
* @return
*/
public String getHashValueByKey(String key, String field) {
String str = jedis.hget(key, field);
return str;
}
/**
* 擷取指定hash表中所有字段
* @param key
* @return
* @throws ConfigurationException
*/
public Map<String, String> getHash(String key){
return jedis.hgetAll(key);
}
public String setHash(String key, Map<String, String> map){
return jedis.hmset(key, map);
}
public void setHashAndTime(String key, Map<String, String> map,int times){
jedis.hmset(key, map);
jedis.expire(key, times);
}
public long del(String key) {
long lon = jedis.del(key);
return lon;
}
/**
* 擷取非切片額用戶端連接配接,當其餘接口不能解決開發問題時,使用此接口解決redis讀取問題。具體檢視jedis官方api
* @return
*/
public Jedis getJedis() {
return jedis;
}
}
在resoures檔案夾下建立application.properties
内容如下:
server.port=8099
#配置資料源
spring.datasource.url=jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#配置MyBatis的xml檔案路徑
mybatis.mapper-locations: classpath:/mapper/*Mapper.xml
再建立一個config.properties檔案,用來配置項目中用到的一些公共配置,比如:檔案伺服器位址,redis連結資訊等,下面是我寫的一些内容:
#######################################################redis config###############################################################
maxIdle=1000
maxTotal=1000
maxWaitMillis=10000
testOnBorrow=false
host=10.0.0.30
port=6379
name=master
file_server_ip=10.0.0.30
file_server_port=22
fole_server_user=root
file_server_password=qwe123
接下來需要建立一個MyBatis的xml檔案映射的目錄,也就是在application.properties裡面配置的:mybatis.mapper-locations: classpath:/mapper/*Mapper.xml
如下圖:
mapper内放置的就是你的xml檔案
接下來,建立一個啟動類GnayEyApplication.java和Swagger.java類
如下
package com.gnayey.startup;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableTransactionManagement(proxyTargetClass = true)
@EnableSwagger2
@ComponentScan(basePackages = "com.gnayey.exception")
@ComponentScan(basePackages = "com.gnayey.controller")
@ComponentScan(basePackages = "com.gnayey.service")
@MapperScan("com.gnayey.mapper")
@SpringBootApplication
public class GnayEyApplication {
public static void main(String[] args) {
SpringApplication.run(GnayEyApplication.class, args);
}
}
package com.gnayey.startup;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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;
@Configuration
@EnableSwagger2
public class Swagger2 implements WebMvcConfigurer {
// 接口版本号
private final String version = "1.0";
// 接口大标題
private final String title = "GnayEyTestProject";
// 具體的描述
private final String description = "公共資料服務接口文檔";
// basePackage
private final String basePackage = "com.gnayey.controller";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
}
目錄結構如下:
到這,一個SpringBoot架構就完成了,下面我們寫一個登陸接口,并給項目配置攔截器,使用redis來儲存使用者登陸資訊。直接上代碼:
攔截器配置類:如上圖中的WebAppConfig.java
package com.gnayey.startup;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.gnayey.interceptor.InterceptorConfig;
@EnableWebMvc
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Bean
InterceptorConfig localInterceptor() {
return new InterceptorConfig();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localInterceptor())
.addPathPatterns("/v1/**")
.excludePathPatterns("/v1/login/**/")//配置登陸接口不被攔截
.excludePathPatterns( "/swagger-ui.html/**");//配置swagger位址不被攔截
WebMvcConfigurer.super.addInterceptors(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
下面是攔截器的具體實作,裡面是寫你的具體業務
package com.gnayey.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class InterceptorConfig implements HandlerInterceptor {
@Autowired
private GnayeyLoginServicegnayeyLoginService;*/
/**
* 進入controller層之前攔截請求
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//擷取前端tocken
String token = httpServletRequest.getParameter("token");
if(token != null) {
if(token.length() > 0) {
SchoolfellowUserLoginResVo schoolfellowUserLoginRepVo = schoolfellowLoginService.getLoginedUserInfo(token);
if (schoolfellowUserLoginRepVo == null) {
return false;
} else {
return true;
}
}
}
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
下面是DAO類,其中包含了Lombok的用法,
Lombok的用法參考:
https://www.cnblogs.com/heyonggang/p/8638374.html
package com.gnayey.entity;
import lombok.Getter;
import lombok.Setter;
public class SysUserInfoDo {
@Getter
@Setter
private String id;
@Getter
@Setter
private String loginName;
@Getter
@Setter
private String userName;
}
下面是mapperj接口
package com.gnayey.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.gnayey.entity.SysUserInfoDo;
@Mapper
public interface SysUserInfoMapper {
/**
* 根據使用者登入名和密碼查詢
* @param loginName password
* @return
*/
SysUserInfoDo selectByLoginNameAndPassword(@Param("loginName")String loginName, @Param("password")String password);
}
下面是MyBatis的.xml檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gnayey.mapper.SysUserInfoMapper">
<resultMap id="sysUserInfoDo" type="com.gnayey.entity.SysUserInfoDo">
<id column="ID" property="id" jdbcType="VARCHAR" />
<result column="LOGINNAME" property="loginName" jdbcType="VARCHAR" />
<result column="USERNAME" property="userName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_List" >
ID, LOGINNAME, USERNAME
</sql>
<select id="selectByLoginNameAndPassword" resultMap="sysUserInfoDo" >
SELECT
<include refid="Base_List" />
FROM sys_userInfo
WHERE LOGINNAME = #{loginName}
AND PASSWORD= #{password}
</select>
</mapper>
下面是我們的Controller類,代碼如下
package com.gnayey.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gnayey.common.request.vo.GnayeyUserLoginResVo;
import com.gnayey.common.response.vo.ResponseData;
import com.gnayey.common.util.value.SystemCodeConstant;
import com.gnayey.service.GnayeyLoginService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
@Controller
@RequestMapping("/v1/login")
public class GnayeySysUserLoginController {
@Autowired
private GnayeyLoginService gnayeyLoginService;
@ApiOperation(value = "使用者登陸", notes = "注意事項")
@ApiImplicitParams({
@ApiImplicitParam(name = "loginName", value = "登入名", required = true, paramType = "query", example = ""),
@ApiImplicitParam(name = "password", value = "登陸密碼", required = true, paramType = "query", example = "")
})
@RequestMapping(value="/userLogin",method=RequestMethod.POST)
@ResponseBody
public ResponseData userLogin(@RequestParam(value="loginName") String loginName, @RequestParam(value="password") String password) {
GnayeyUserLoginResVo response = gnayeyLoginService.userLogion(loginName, password);
if (response != null) {
return new ResponseData(SystemCodeConstant.RIGHT_CODE, response, "請求成功");
}else{
return new ResponseData(SystemCodeConstant.ERROR_CODE, response, "請求失敗");
}
}
}
下面是登陸業務接口
package com.gnayey.service;
import com.gnayey.common.request.vo.GnayeyUserLoginResVo;
public interface GnayeyLoginService {
/**
* 使用者登陸擷取個人資訊
* @param loginName 使用者名
* @return
*/
public GnayeyUserLoginResVo userLogion(String userCode, String password);
/**
* 從redis中擷取使用者的登陸資訊
* @param tocken 使用者登陸tocken
* @return
*/
public GnayeyUserLoginResVo getLoginedUserInfoByRedis(String token);
/**
* 使用者登出,從redis中删除使用者的登陸資訊
* @param tocken 使用者登陸tocken
* @return
*/
public void processUserLogout(String token);
/**
* 清楚redis中的token資料
* @param tocken 使用者登陸tocken
* @return
*/
void extendUserTokenTime(String token);
}
下面是接口的實作,具體業務寫在這裡面,有詳細的注解:
package com.gnayey.service;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gnayey.common.request.vo.GnayeyUserLoginResVo;
import com.gnayey.common.util.Base64Util;
import com.gnayey.common.vo.GnayeyLoginUserInfoTokenVo;
import com.gnayey.entity.SysUserInfoDo;
import com.gnayey.mapper.SysUserInfoMapper;
import com.gnayey.redis.RedisClient;
@Service
public class GnayeyLoginServiceImpl implements GnayeyLoginService {
@Autowired
private SysUserInfoMapper sysUserInfoMapper;
@Override
public GnayeyUserLoginResVo userLogion(String loginName, String password) {
String loginNameB = Base64Util.decodeData(loginName);//登陸名解密
String passwordB = Base64Util.decodeData(password);//登陸密碼解密
SysUserInfoDo sysUserInfeoDo = sysUserInfoMapper.selectByLoginNameAndPassword(loginNameB, passwordB);
if(sysUserInfeoDo == null) {
return null;
}
//生成token,并将其寫入到redis中,key值為token
return addUserLoginInfoToRedis(sysUserInfeoDo);
}
@Override
public GnayeyUserLoginResVo getLoginedUserInfoByRedis(String token) {
GnayeyUserLoginResVo response = new GnayeyUserLoginResVo();
RedisClient redisClient = new RedisClient();
Map<String, String> redisUserInfo = redisClient.getHash(token);
if(redisUserInfo.size() == 0){
return null;
}
//從redis中可擷取到使用者的登陸資訊
response.setUserId(redisUserInfo.get(GnayeyLoginUserInfoTokenVo.REDIS_KEY_USERID));
response.setToken(token);
response.setLoginName(redisUserInfo.get(GnayeyLoginUserInfoTokenVo.REDIS_KEY_LOGINNAME));
response.setUserName(redisUserInfo.get(GnayeyLoginUserInfoTokenVo.REDIS_KEY_USERNAME));
redisClient.closeResource();//記得每次操作redis最後都必須要執行關閉方法,不然會導緻資源占用,系統記憶體爆滿
return response;
}
@Override
public void processUserLogout(String token) {
RedisClient redisClient = new RedisClient();
redisClient.del(token);
redisClient.closeResource();
}
private GnayeyUserLoginResVo addUserLoginInfoToRedis(SysUserInfoDo sysUserInfeoDo) {
//生成token
String token = java.util.UUID.randomUUID().toString();
//将token寫入到redis中,key值為token
RedisClient redisClient = new RedisClient();
//儲存至redis的使用者資料
Map<String, String> hash = new HashMap<String, String>();
hash.put(GnayeyLoginUserInfoTokenVo.REDIS_KEY_TOKEN, token);
hash.put(GnayeyLoginUserInfoTokenVo.REDIS_KEY_USERID, sysUserInfeoDo.getId() == null ? "":sysUserInfeoDo.getId());
hash.put(GnayeyLoginUserInfoTokenVo.REDIS_KEY_LOGINNAME, sysUserInfeoDo.getLoginName() == null ? "":sysUserInfeoDo.getLoginName());
hash.put(GnayeyLoginUserInfoTokenVo.REDIS_KEY_USERNAME, sysUserInfeoDo.getUserName() == null ? "":sysUserInfeoDo.getUserName());
//将資料儲存至redis資料庫并設定失效時間
redisClient.setHashAndTime(token, hash, 36000);
redisClient.closeResource();
//傳回給前端的使用者資料
GnayeyUserLoginResVo responseVo = new GnayeyUserLoginResVo();
responseVo.setToken(token);
responseVo.setUserId(sysUserInfeoDo.getId());
responseVo.setLoginName(sysUserInfeoDo.getLoginName());
responseVo.setUserName(sysUserInfeoDo.getUserName());
return responseVo;
}
@Override
public void extendUserTokenTime(String token) {
//延長token時間
RedisClient redisClient = new RedisClient();
Map<String, String> redisUserInfo = redisClient.getHash(token);
redisClient.setHashAndTime(token, redisUserInfo, 36000);
redisClient.closeResource();
}
}
到這裡,一個登陸的接口就完成了,其中包含了Controller互動層,Sercive業務層,Dao持久層,下來啟動程式登陸swagger進行測試:
這是啟動成功後顯示的端口:
接下來,打開浏覽器輸入位址:localhost:8099/swagger-ui.html
注意,項目中用到了Base64加密,是以在swagger測試輸入使用者名和密碼時要進行加密
base64加密解密連結:
http://tool.oschina.net/encrypt?type=3
然後點選按鈕Try it out! 進行通路,結果如下:傳回資訊,成功
到這裡就完成了使用者登入接口。全部内容已經寫完。
總結SpringBoot能夠快速的建立一個Spring項目,并通過注解的方式實作快速程式設計,易上手。同時也可以結合很多插件等功能進行業務實作,提高開發效率。
此次内容沒有描述SpringBoot的全局異常捕獲和事務,後面我會繼續發文。