Hi ! 我是小小,今天是本周的第四篇,第四篇主要内容是 Spring Boot + Redis 實作接口幂等性
介紹
幂等性的概念是,任意多次執行所産生的影響都與一次執行産生的影響相同,按照這個含義,最終的解釋是對資料庫的影響隻能是一次性的,不能重複處理。手段如下
資料庫建立唯一索引
token機制
悲觀鎖或者是樂觀鎖
先查詢後判斷
小小主要帶你們介紹Redis實作自動幂等性。其原理如下圖所示。
實作過程
引入 maven 依賴
org.springframework.boot
spring-boot-starter-data-redis
spring 配置檔案寫入
server.port=8080
core.datasource.druid.enabled=true
core.datasource.druid.url=jdbc:mysql://192.168.1.225:3306/?useUnicode=true&characterEncoding=UTF-8
core.datasource.druid.username=root
core.datasource.druid.password=
core.redis.enabled=true
spring.redis.host=192.168.1.225 #本機的redis位址
spring.redis.port=16379
spring.redis.database=3
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=5s
spring.redis.jedis.pool.min-idle=10
引入 Redis
引入 Spring boot 中的redis相關的stater,後面需要用到 Spring Boot 封裝好的 RedisTemplate
package cn.smallmartial.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean setEx(final String key, Object value, long expireTime) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Object get(final String key) {
Object result = null;
ValueOperations operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public boolean remove(final String key) {
if (exists(key)) {
Boolean delete = redisTemplate.delete(key);
return delete;
}
return false;
}
public boolean exists(final String key) {
boolean result = false;
ValueOperations operations = redisTemplate.opsForValue();
if (Objects.nonNull(operations.get(key))) {
result = true;
}
return result;
}
}
自定義注解
自定義一個注解,定義此注解的目的是把它添加到需要實作幂等的方法上,隻要某個方法注解了其,都會自動實作幂等操作。其代碼如下
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIdempotent {
}
token 的建立和實作
token 服務接口,我們建立一個接口,建立token服務,裡面主要是有兩個方法,一個用來建立 token,一個用來驗證token
public interface TokenService {
public String createToken();
public boolean checkToken(HttpServletRequest request) throws Exception;
}
token 的實作類,token中引用了服務的實作類,token引用了 redis 服務,建立token采用随機算法工具類生成随機 uuid 字元串,然後放入 redis 中,如果放入成功,傳回token,校驗方法就是從 header 中擷取 token 的值,如果不存在,直接跑出異常,這個異常資訊可以被直接攔截到,傳回給前端。
package cn.smallmartial.demo.service.impl;
import cn.smallmartial.demo.bean.RedisKeyPrefix;
import cn.smallmartial.demo.bean.ResponseCode;
import cn.smallmartial.demo.exception.ApiResult;
import cn.smallmartial.demo.exception.BusinessException;
import cn.smallmartial.demo.service.TokenService;
import cn.smallmartial.demo.utils.RedisUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.UUID;
@Service
public class TokenServiceImpl implements TokenService {
@Autowired
private RedisUtil redisService;
@Override
public String createToken() {
String str = UUID.randomUUID().toString().replace("-", "");
StringBuilder token = new StringBuilder();
try {
token.append(RedisKeyPrefix.TOKEN_PREFIX).append(str);
redisService.setEx(token.toString(), token.toString(), 10000L);
boolean empty = StringUtils.isEmpty(token.toString());
if (!empty) {
return token.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
public boolean checkToken(HttpServletRequest request) throws Exception {
String token = request.getHeader(RedisKeyPrefix.TOKEN_NAME);
if (StringUtils.isEmpty(token)) {// header中不存在token
token = request.getParameter(RedisKeyPrefix.TOKEN_NAME);
if (StringUtils.isEmpty(token)) {// parameter中也不存在token
throw new BusinessException(ApiResult.BADARGUMENT);
}
}
if (!redisService.exists(token)) {
throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
}
boolean remove = redisService.remove(token);
if (!remove) {
throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
}
return true;
}
}
攔截器的配置
用于攔截前端的 token,判斷前端的 token 是否有效
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Bean
public AuthInterceptor authInterceptor() {
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor());
// .addPathPatterns("/ksb
@RestController
public class BusinessController {
@Autowired
private TokenService tokenService;
@GetMapping("/get/token")
public Object getToken(){
String token = tokenService.createToken();
return ResponseUtil.ok(token) ;
}
@AutoIdempotent
@GetMapping("/test/Idempotence")
public Object testIdempotence() {
String token = "接口幂等性測試";
return ResponseUtil.ok(token) ;
}
}
用浏覽器進行通路
用擷取到的token第一次通路
用擷取到的token再次通路
可以看到,第二次通路失敗,即,幂等性驗證通過。
關于作者
我是小小,雙魚座的程式猿,活在一線城市,我們下期再見。
小明菜市場
推薦閱讀
給我個好看再走好嗎?