前言
网关作为整个微服务入口,在网关做认证受权既能够提前过滤不非法或过期的申请,又能让其余服务专做本身业务,不再关怀令牌和权限问题。在集成过程中,选用的微服务版本为 Greenwich.SR2,springboot 版本以及 security 版本都为2.1.6.RELEASE,security 每个版本的的实现有蛮大差别的。比方在 2.0.1.RELEASE 版在装载权限 tag 的时候是不须要带ROLE_
前缀的,而 2.1.6.RELEASE 看源码得悉须要本人拼接前缀。因为公司加密问题,我的项目不能搁置外网,后续篇幅可能偏长,尽量每一步都贴革除,不便初学者少踩坑。但原理就读者本人去领会。
构建我的项目
eureka : 注册核心
common : 专用模块,搁置其余服务专用的局部,能够不必
api-gateway : zuul 集成 security 实现登录认证
auth-center : zuul 集成 security 实现认证受权
父 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.babaznkj.com</groupId>
<artifactId>zuul-auth</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>eureka</module>
<module>api-gateway</module>
<module>common</module>
<module>auth-center</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
<mybatis.starter.version>1.3.2</mybatis.starter.version>
<druid.starter.version>1.1.9</druid.starter.version>
<mapper.starter.version>2.0.2</mapper.starter.version>
<leyou.latest.version>1.0.0-SNAPSHOT</leyou.latest.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<!-- springCloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.babaznkj.com</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- <configuration>-->
<!-- <!–1. 这里要指定你的 springboot 我的项目的主启动类的全类名 -->
<!-- 2. 大家不要把这个插件放到父我的项目的依赖中,哪个我的项目须要打包,就放到哪个我的项目的依赖下 –>-->
<!-- <mainClass>com.baba.security.gateway</mainClass>-->
<!-- </configuration>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <goals>-->
<!-- <goal>repackage</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
</plugin>
</plugins>
</build>
</project>
- common 模块
-
JwtProperties.java
,这个版本验证 Authorization 的时候截取了前 6 位,且已Bearer
结尾,故在生成 jwt 的时候要拼接前缀,这个文件就用来读取默认配置的。package com.baba.security.common.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @Author wulongbo * @Date 2021/11/4 9:49 * @Version 1.0 */ @Data @Component @ConfigurationProperties("baba.security.jwt") public class JwtProperties { private String secret; private String url; private String header; private String prefix; private Integer expiration; private String language; }
-
JwtTokenAuthenticationFilter.java
, 因为过滤器中无奈注入 bean,故采纳从 spring 上下文中获取。做全局异样解决,要抛出自定义异样能够先抛如 controller 中,当然这里采纳了另外一种形式。这里实现了动静验签以及惟一登录。package com.baba.security.common.config; import com.baba.security.common.constant.RedisConstant; import com.baba.security.common.enums.ResultCode; import com.baba.security.common.exception.DefinitException; import com.baba.security.common.utils.JwtUtils; import com.baba.security.common.utils.RedisUtils; import com.baba.security.common.utils.SpringUtils; import io.jsonwebtoken.JwtException; import org.springframework.context.ApplicationContext; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.servlet.HandlerExceptionResolver; import javax.servlet.FilterChain; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Authenticate requests with header 'Authorization: Bearer jwt-token'. * * @author wulongbo 2021/10/18 */ public class JwtTokenAuthenticationFilter extends OncePerRequestFilter { // private final JwtAuthenticationConfig config; private final JwtProperties config; public JwtTokenAuthenticationFilter(JwtProperties config) {this.config = config;} @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse rsp, FilterChain filterChain) throws ServletException, IOException { HandlerExceptionResolver resolver = null; try {RedisUtils redisUtil = SpringUtils.getBean(RedisUtils.class); // filter 过滤器应用 Autowired 注入 Bean 为 null ServletContext context = req.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context); resolver = ctx.getBean("handlerExceptionResolver", HandlerExceptionResolver.class); String userAgent = req.getHeader("user-agent").toLowerCase(); String salt = null; // 获取 token String token = req.getHeader(config.getHeader()); if (token != null && token.startsWith(config.getPrefix() + " ")) {token = token.replace(config.getPrefix() + "",""); String id = redisUtil.get(token); if (StringUtils.isEmpty(id)) {resolver.resolveException(req, rsp, null, new DefinitException(ResultCode.REDIS_CACHE_BLANK)); return; } if (userAgent.indexOf("micromessenger") != -1) {// 微信} else if (userAgent.indexOf("android") != -1 || userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1 || userAgent.indexOf("ipod") != -1) { // 安卓 或者 苹果 salt = redisUtil.get(RedisConstant.PREFIX_APP + id); } else { // 电脑 salt = redisUtil.get(RedisConstant.PREFIX_WEB + id); } if (StringUtils.isEmpty(salt)) {resolver.resolveException(req, rsp, null, new DefinitException(ResultCode.REDIS_SALT_BLANK)); return; } String username = JwtUtils.getUsername(token,salt); if (username != null) {List<SimpleGrantedAuthority> roles = JwtUtils.getUserRole(token,salt); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username, null, roles)); } } // resolver.resolveException(req, rsp, null, new JwtException(ResultCode.TOKEN_EXCEPTION.getMessage())); filterChain.doFilter(req, rsp); } catch (JwtException e) {resolver.resolveException(req, rsp, null, new JwtException(ResultCode.SAFETY_INVALID.getMessage())); } } }
-
RedisConstant.java
, 常量类。package com.baba.security.common.constant; /** * @author wulongbo 2021/10/18 */ public interface RedisConstant { String TOKEN_TEMPLATE = "token_%s"; String PREFIX_APP = "bbznkj_app_"; String PREFIX_WEB = "bbznkj_web_"; }
-
ResultCode.java
, 枚举类能够标准响应,如是多国语言的零碎能够思考实用 redis 来解决。package com.baba.security.common.enums; /** * @Author wulongbo * @Date 2021/10/27 14:13 * @Version 1.0 */ /** * 异样解决状态码 */ public enum ResultCode {SUCCESS(0, "申请胜利"), FAILED(1001, "响应失败"), Unknown_Exception(-1, "未知异样"), SAFETY_INVALID(208,"该账号已在其余设施登录,签名已生效,请从新登录"), REDIS_CACHE_BLANK(6379, "缓存已生效, 请从新登录"), REQUEST_URL_WRONG(401, "申请地址不存在"), REQUEST_BLANK(403, "申请接口无权限拜访"), REDIS_SALT_BLANK(6333,"签名值缓存生效"), USER_NOT_FOUND(10001, "没有找到此用户"), USERNAME_NOT_BLANK(10002, "用户名不能为空"), USERNAME_EXIST(10003, "用户名曾经存在"), USERTYPE_ERROR(100031, "用户类型不正确"), PHONE_WROND(10004, "手机号不正确"), SMS_CODE_ERROR(10007, "手机验证码不正确"), PHONE_EXIST(10008, "手机号曾经存在"), USER_EMPTY_EXCEPTION(10009, "用户名、手机号或者邮箱为空"), USER_TOKEN_EXCEPTION(10010, "从 TOKEN 中未查到相干用户信息"), USERNAME_PASSWORD_EXCEPTION(10011, "用户名或者明码谬误"), EMAIL_SERVER_ECCEPTION(10012, "阿里云邮件服务端出错"), EMAIL_CLIENT_ECCEPTION(10013, "阿里云邮件客户端出错"), EMAIL_SEND_ECCEPTION(10014, "阿里云邮件发送出错"), EMAIL_WROND(10015, "邮箱不正确"), EMAIL_CODE_WROND(10016, "邮箱验证码不正确"), EMAIL_EXIST(10017, "邮箱曾经存在"), LOGIN_METHOD_WROND(209, "登录明码不正确"), CODE_EMPTY(10019, "验证码不为空"), PASSWORD_EMPTY(10020, "明码不为空"), TOKEN_EXCEPTION(10021, "TOKEN 认证出错"), USER_AUTH_FAILD(10022, "用户认证失败"), USER_AUTH_SUCCESS(200, "用户认证受权胜利"), USER_ACCESS_DENIED(10023, "用户无权限登录"), CODE_SEND_FAILD(10030, "验证码发送失败"), ACTION_MONGODB_ERROR(10100, "操作 MONGODB 数据库出错"), OPERATION_TOO_FREQUENT(10101, "申请过于频繁,请稍候再试"), CODE_EXIST(10023,"编号已存在"), TESTCODE_ERROR(10036,"提交数已达下限"), NAME_EXIST(10024,"名称已存在"), NOT_EXIST_EMAIL(10025,"该企业用户没有调配邮箱"), MAIL_REACH_MAX(10026,"达到收取邮箱下限"), MAIL_NEW_NOTEXIST(10027,"邮箱中没有可导入的简历"), PWD_CONFIRM_ERROR(10029,"两次明码不统一"), PWD_ERROR(10030,"明码不正确"), ENTER_OR_TALENT_NOT_EXITS(10028,"企业或人才库简历不存在"), PHONE_EMPTY(10031, "手机号不能为空"), EMAIL_EMPTY(10032, "邮箱不能为空"), NO_USABLE_MAIL(10040,"没有可用邮箱"), DEVICE_ID_EMPTY(10052,"设施 ID:deviceId 不能为空"), DELETE_CONNECT_ERROR(10053,"删除 connect 出错"); private int code; private String message; ResultCode(int code, String message) { this.code = code; this.message = message; } public int getCode() {return code;} public String getMessage() {return message;} }
-
ApiException.java
、DefinitException.java
、JWTAuthenticationEntryPoint.java
、ExceptionControllerAdvice.java
、SimpleAccessDeniedHandler.java
、SimpleAuthenticationEntryPoint.java
、:自定义异样类,用于全局异样解决。package com.baba.security.common.exception; import lombok.Getter; /** * @Author wulongbo * @Date 2021/10/27 11:58 * @Version 1.0 * 自定义异样 */ @Getter // 只有 getter 办法,无需 setter public class ApiException extends RuntimeException { private int code; private String msg; public ApiException() {this(1001, "接口谬误"); } public ApiException(String msg) {this(1001, msg); } public ApiException(int code, String msg) {super(msg); this.code = code; this.msg = msg; } }
package com.baba.security.common.exception;
import com.baba.security.common.enums.ResultCode;
import lombok.Data;
/**
* @Author wulongbo
* @Date 2021/10/28 11:28
* @Version 1.0
*/
@Data
public class DefinitException extends RuntimeException {
private ResultCode resultCode;
private int code;
private String msg;
public DefinitException() {this(1001, "接口谬误");
}
public DefinitException(ResultCode resultCode) {this(resultCode.getCode(), resultCode.getMessage());
this.resultCode=resultCode;
}
public DefinitException(int code, String msg) {super(msg);
this.code = code;
this.msg = msg;
}
}
package com.baba.security.common.exception;
import com.baba.security.common.enums.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
* @Author wulongbo
* @Date 2021/11/2 17:08
* @Version 1.0
*/
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {HashMap<String, Object> map = new HashMap<>(3);
map.put("uri", request.getRequestURI());
map.put("code", ResultCode.REQUEST_URL_WRONG.getCode());
map.put("msg", ResultCode.REQUEST_URL_WRONG.getMessage());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(new ObjectMapper().writeValueAsString(map));
}
}
package com.baba.security.common.handler;
import com.baba.security.common.enums.ResultCode;
import com.baba.security.common.exception.ApiException;
import com.baba.security.common.exception.DefinitException;
import com.baba.security.common.vo.ResultVO;
import io.jsonwebtoken.JwtException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @Author wulongbo
* @Date 2021/10/27 12:00
* @Version 1.0
* 全局异样管制类
*/
@RestControllerAdvice
public class ExceptionControllerAdvice {@ExceptionHandler(DefinitException.class)
public ResultVO<String> handleDefinitException(DefinitException e) {
// 留神哦,这里返回类型是自定义响应体
return new ResultVO<>(e.getResultCode());
}
@ExceptionHandler(ApiException.class)
public ResultVO<String> handleApiException(ApiException e) {
// 留神哦,这里返回类型是自定义响应体
return new ResultVO<>(ResultCode.FAILED, e.getMsg());
}
@ExceptionHandler(JwtException.class)
public ResultVO<String> handleJwtException(JwtException e) {return new ResultVO<>(ResultCode.SAFETY_INVALID);
}
}
package com.baba.security.common.handler;
import com.baba.security.common.enums.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
/**
* @Author wulongbo
* @Date 2021/10/28 13:49
* @Version 1.0
*/
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
//todo your business
HashMap<String, Object> map = new HashMap<>(3);
map.put("uri", request.getRequestURI());
map.put("code", ResultCode.REQUEST_BLANK.getCode());
map.put("msg", ResultCode.REQUEST_BLANK.getMessage());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper objectMapper = new ObjectMapper();
String resBody = objectMapper.writeValueAsString(map);
PrintWriter printWriter = response.getWriter();
printWriter.print(resBody);
printWriter.flush();
printWriter.close();
// throw new DefinitException(ResultCode.REQUEST_BLANK);
}
}
package com.baba.security.common.handler;
import com.baba.security.common.enums.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
/**
* @Author wulongbo
* @Date 2021/10/28 13:49
* @Version 1.0
*/
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {HashMap<String, Object> map = new HashMap<>(2);
map.put("uri", request.getRequestURI());
map.put("code", ResultCode.USER_AUTH_FAILD.getCode());
map.put("msg", ResultCode.USER_AUTH_FAILD.getMessage());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper objectMapper = new ObjectMapper();
String resBody = objectMapper.writeValueAsString(map);
PrintWriter printWriter = response.getWriter();
printWriter.print(resBody);
printWriter.flush();
printWriter.close();}
}
-
这里就是工具类啦,间接贴不再阐明。
package com.baba.security.common.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class JwtUtils { public static final String TOKEN_HEADER = "token"; public static final String TOKEN_PREFIX = "Bearer"; private static final String SUBJECT = "mayikt"; private static final long EXPIRITION = 1000 * 24 * 60 * 60 * 7; private static final String APPSECRET_KEY = "secret"; private static final String ROLE_CLAIMS = "roles"; private static final String LANGUAGE = "language"; public static String generateJsonWebToken(Authentication auth,String secretKey,String language) {Instant now = Instant.now(); String token = Jwts.builder() .setSubject(auth.getName()) .claim(LANGUAGE,language) .claim(ROLE_CLAIMS, auth.getAuthorities().stream() .map(GrantedAuthority::getAuthority).collect(Collectors.toList())) .setIssuedAt(Date.from(now)) .setExpiration(Date.from(now.plusSeconds(EXPIRITION))) .signWith(SignatureAlgorithm.HS256, secretKey.getBytes()) .compact(); return token; } /** * 生成 token * * @param username * @param role * @return */ public static String createToken(String username, String role) {Map<String, Object> map = new HashMap<>(); map.put(ROLE_CLAIMS, role); String token = Jwts .builder() .setSubject(username) .setClaims(map) .claim("username", username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION)) .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact(); return token; } public static Claims checkJWT(String token) { try {final Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody(); return claims; } catch (Exception e) {e.printStackTrace(); return null; } } /** * 获取用户名 * * @param token * @return */ public static String getUsername(String token, String secretKey) {Claims claims = Jwts.parser() .setSigningKey(secretKey.getBytes()) .parseClaimsJws(token) .getBody(); String username = claims.getSubject(); return username; } /** * 获取用户角色 * * @param token * @return */ public static List<SimpleGrantedAuthority> getUserRole(String token, String secretKey) {Claims claims = Jwts.parser() .setSigningKey(secretKey.getBytes()) .parseClaimsJws(token) .getBody(); List<String> authorities = claims.get(ROLE_CLAIMS, List.class); return authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); } /** * 获取用户角色 * * @param token * @return */ public static List<SimpleGrantedAuthority> getUserRole2(String token) {Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY.getBytes()).parseClaimsJws(token).getBody(); List<String> authorities = claims.get("authorities", List.class); List<SimpleGrantedAuthority> roles = authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); return roles; } /** * 是否过期 * * @param token * @return */ public static boolean isExpiration(String token) {Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody(); return claims.getExpiration().before(new Date()); } }
package com.baba.security.common.utils;
import java.security.MessageDigest;
public class MD5Util {
private static final String SALT = "mayikt";
public static String encode(String password) {
password = password + SALT;
MessageDigest md5 = null;
try {md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();}
public static void main(String[] args) {System.out.println(MD5Util.encode("123456"));
}
}
package com.baba.security.common.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils<T> {
@Autowired
private StringRedisTemplate redisTemplate;
public void setRedisTemplate(StringRedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;}
public StringRedisTemplate getRedisTemplate() {return this.redisTemplate;}
/** -------------------key 相干操作 --------------------- */
/**
* 删除 key
*
* @param key
*/
public void delete(String key) {redisTemplate.delete(key);
}
/**
* 批量删除 key
*
* @param keys
*/
public void delete(Collection<String> keys) {redisTemplate.delete(keys);
}
/**
* 序列化 key
*
* @param key
* @return
*/
public byte[] dump(String key) {return redisTemplate.dump(key);
}
/**
* 是否存在 key
*
* @param key
* @return
*/
public Boolean hasKey(String key) {return redisTemplate.hasKey(key);
}
/**
* 设置过期工夫
*
* @param key
* @param timeout
* @param unit
* @return
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {return redisTemplate.expire(key, timeout, unit);
}
/**
* 设置过期工夫
*
* @param key
* @param date
* @return
*/
public Boolean expireAt(String key, Date date) {return redisTemplate.expireAt(key, date);
}
/**
* 查找匹配的 key
*
* @param pattern
* @return
*/
public Set<String> keys(String pattern) {return redisTemplate.keys(pattern);
}
/**
* 将以后数据库的 key 挪动到给定的数据库 db 当中
*
* @param key
* @param dbIndex
* @return
*/
public Boolean move(String key, int dbIndex) {return redisTemplate.move(key, dbIndex);
}
/**
* 移除 key 的过期工夫,key 将长久放弃
*
* @param key
* @return
*/
public Boolean persist(String key) {return redisTemplate.persist(key);
}
/**
* 返回 key 的残余的过期工夫
*
* @param key
* @param unit
* @return
*/
public Long getExpire(String key, TimeUnit unit) {return redisTemplate.getExpire(key, unit);
}
/**
* 返回 key 的残余的过期工夫
*
* @param key
* @return
*/
public Long getExpire(String key) {return redisTemplate.getExpire(key);
}
/**
* 从以后数据库中随机返回一个 key
*
* @return
*/
public String randomKey() {return redisTemplate.randomKey();
}
/**
* 批改 key 的名称
*
* @param oldKey
* @param newKey
*/
public void rename(String oldKey, String newKey) {redisTemplate.rename(oldKey, newKey);
}
/**
* 仅当 newkey 不存在时,将 oldKey 改名为 newkey
*
* @param oldKey
* @param newKey
* @return
*/
public Boolean renameIfAbsent(String oldKey, String newKey) {return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 返回 key 所贮存的值的类型
*
* @param key
* @return
*/
public DataType type(String key) {return redisTemplate.type(key);
}
/** -------------------string 相干操作 --------------------- */
/**
* 设置指定 key 的值
*
* @param key
* @param value
*/
public void set(String key, String value) {redisTemplate.opsForValue().set(key, value);
}
/**
* 获取指定 key 的值
*
* @param key
* @return
*/
public String get(String key) {return redisTemplate.opsForValue().get(key);
}
/**
* 返回 key 中字符串值的子字符
*
* @param key
* @param start
* @param end
* @return
*/
public String getRange(String key, long start, long end) {return redisTemplate.opsForValue().get(key, start, end);
}
/**
* 将给定 key 的值设为 value,并返回 key 的旧值(old value)
*
* @param key
* @param value
* @return
*/
public String getAndSet(String key, String value) {return redisTemplate.opsForValue().getAndSet(key, value);
}
/**
* 对 key 所贮存的字符串值,获取指定偏移量上的位(bit)
*
* @param key
* @param offset
* @return
*/
public Boolean getBit(String key, long offset) {return redisTemplate.opsForValue().getBit(key, offset);
}
/**
* 批量获取
*
* @param keys
* @return
*/
public List<String> multiGet(Collection<String> keys) {return redisTemplate.opsForValue().multiGet(keys);
}
/**
* 设置 ASCII 码, 字符串 'a' 的 ASCII 码是 97, 转为二进制是 '01100001', 此办法是将二进制第 offset 位值变为 value
*
* @param key 地位
* @param value 值,true 为 1, false 为 0
* @return
*/
public boolean setBit(String key, long offset, boolean value) {return redisTemplate.opsForValue().setBit(key, offset, value);
}
/**
* 将值 value 关联到 key,并将 key 的过期工夫设为 timeout
*
* @param key
* @param value
* @param timeout 过期工夫
* @param unit 工夫单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
* 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
*/
public void setEx(String key, String value, long timeout, TimeUnit unit) {redisTemplate.opsForValue().set(key, value, timeout, unit);
}
/**
* 只有在 key 不存在时设置 key 的值
*
* @param key
* @param value
* @return 之前曾经存在返回 false, 不存在返回 true
*/
public boolean setIfAbsent(String key, String value) {return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* 用 value 参数覆写给定 key 所贮存的字符串值,从偏移量 offset 开始
*
* @param key
* @param value
* @param offset 从指定地位开始覆写
*/
public void setRange(String key, String value, long offset) {redisTemplate.opsForValue().set(key, value, offset);
}
/**
* 获取字符串的长度
*
* @param key
* @return
*/
public Long size(String key) {return redisTemplate.opsForValue().size(key);
}
/**
* 批量增加
*
* @param maps
*/
public void multiSet(Map<String, String> maps) {redisTemplate.opsForValue().multiSet(maps);
}
/**
* 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在
*
* @param maps
* @return 之前曾经存在返回 false, 不存在返回 true
*/
public boolean multiSetIfAbsent(Map<String, String> maps) {return redisTemplate.opsForValue().multiSetIfAbsent(maps);
}
/**
* 减少(自增长), 正数则为自减
*
* @param key
* @return
*/
public Long incrBy(String key, long increment) {return redisTemplate.opsForValue().increment(key, increment);
}
/**
* @param key
* @return
*/
public Double incrByFloat(String key, double increment) {return redisTemplate.opsForValue().increment(key, increment);
}
/**
* 追加到开端
*
* @param key
* @param value
* @return
*/
public Integer append(String key, String value) {return redisTemplate.opsForValue().append(key, value);
}
/** -------------------hash 相干操作 ------------------------- */
/**
* 获取存储在哈希表中指定字段的值
*
* @param key
* @param field
* @return
*/
public T hGet(String key, String field) {return (T)redisTemplate.opsForHash().get(key, field);
}
/**
* 获取所有给定字段的值
*
* @param key
* @return
*/
public Map<Object, Object> hGetAll(String key) {return redisTemplate.opsForHash().entries(key);
}
/**
* 获取所有给定字段的值
*
* @param key
* @param fields
* @return
*/
public List<T> hMultiGet(String key, Collection<Object> fields) {return (List<T>)redisTemplate.opsForHash().multiGet(key, fields);
}
public void hPut(String key, String hashKey, String value) {redisTemplate.opsForHash().put(key, hashKey, value);
}
public void hPut(String key, String hashKey, Integer value) {redisTemplate.opsForHash().put(key, hashKey, value);
}
public void hPutAll(String key, Map<String, String> maps) {redisTemplate.opsForHash().putAll(key, maps);
}
/**
* 仅当 hashKey 不存在时才设置
*
* @param key
* @param hashKey
* @param value
* @return
*/
public Boolean hPutIfAbsent(String key, String hashKey, String value) {return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
}
/**
* 删除一个或多个哈希表字段
*
* @param key
* @param fields
* @return
*/
public Long hDelete(String key, Object... fields) {return redisTemplate.opsForHash().delete(key, fields);
}
/**
* 查看哈希表 key 中,指定的字段是否存在
*
* @param key
* @param field
* @return
*/
public boolean hExists(String key, String field) {return redisTemplate.opsForHash().hasKey(key, field);
}
/**
* 为哈希表 key 中的指定字段的整数值加上增量 increment
*
* @param key
* @param field
* @param increment
* @return
*/
public Long hIncrBy(String key, Object field, long increment) {return redisTemplate.opsForHash().increment(key, field, increment);
}
/**
* 为哈希表 key 中的指定字段的整数值加上增量 increment
*
* @param key
* @param field
* @param delta
* @return
*/
public Double hIncrByFloat(String key, Object field, double delta) {return redisTemplate.opsForHash().increment(key, field, delta);
}
/**
* 获取所有哈希表中的字段
*
* @param key
* @return
*/
public Set<T> hKeys(String key) {return (Set<T>) redisTemplate.opsForHash().keys(key);
}
/**
* 获取哈希表中字段的数量
*
* @param key
* @return
*/
public Long hSize(String key) {return redisTemplate.opsForHash().size(key);
}
/**
* 获取哈希表中所有值
*
* @param key
* @return
*/
public List<T> hValues(String key) {return (List<T>) redisTemplate.opsForHash().values(key);
}
/**
* 迭代哈希表中的键值对
*
* @param key
* @param options
* @return
*/
public Cursor<Map.Entry<Object, Object>> hScan(String key, ScanOptions options) {return redisTemplate.opsForHash().scan(key, options);
}
/** ------------------------list 相干操作 ---------------------------- */
/**
* 通过索引获取列表中的元素
*
* @param key
* @param index
* @return
*/
public String lIndex(String key, long index) {return redisTemplate.opsForList().index(key, index);
}
/**
* 获取列表指定范畴内的元素
*
* @param key
* @param start 开始地位, 0 是开始地位
* @param end 完结地位, - 1 返回所有
* @return
*/
public List<String> lRange(String key, long start, long end) {return redisTemplate.opsForList().range(key, start, end);
}
/**
* 存储在 list 头部
*
* @param key
* @param value
* @return
*/
public Long lLeftPush(String key, String value) {return redisTemplate.opsForList().leftPush(key, value);
}
/**
* @param key
* @param value
* @return
*/
public Long lLeftPushAll(String key, String... value) {return redisTemplate.opsForList().leftPushAll(key, value);
}
/**
* @param key
* @param value
* @return
*/
public Long lLeftPushAll(String key, Collection<String> value) {return redisTemplate.opsForList().leftPushAll(key, value);
}
/**
* 当 list 存在的时候才退出
*
* @param key
* @param value
* @return
*/
public Long lLeftPushIfPresent(String key, String value) {return redisTemplate.opsForList().leftPushIfPresent(key, value);
}
/**
* 如果 pivot 存在, 再 pivot 后面增加
*
* @param key
* @param pivot
* @param value
* @return
*/
public Long lLeftPush(String key, String pivot, String value) {return redisTemplate.opsForList().leftPush(key, pivot, value);
}
/**
* @param key
* @param value
* @return
*/
public Long lRightPush(String key, String value) {return redisTemplate.opsForList().rightPush(key, value);
}
/**
* @param key
* @param value
* @return
*/
public Long lRightPushAll(String key, String... value) {return redisTemplate.opsForList().rightPushAll(key, value);
}
/**
* @param key
* @param value
* @return
*/
public Long lRightPushAll(String key, Collection<String> value) {return redisTemplate.opsForList().rightPushAll(key, value);
}
/**
* 为已存在的列表增加值
*
* @param key
* @param value
* @return
*/
public Long lRightPushIfPresent(String key, String value) {return redisTemplate.opsForList().rightPushIfPresent(key, value);
}
/**
* 在 pivot 元素的左边增加值
*
* @param key
* @param pivot
* @param value
* @return
*/
public Long lRightPush(String key, String pivot, String value) {return redisTemplate.opsForList().rightPush(key, pivot, value);
}
/**
* 通过索引设置列表元素的值
*
* @param key
* @param index 地位
* @param value
*/
public void lSet(String key, long index, String value) {redisTemplate.opsForList().set(key, index, value);
}
/**
* 移出并获取列表的第一个元素
*
* @param key
* @return 删除的元素
*/
public String lLeftPop(String key) {return redisTemplate.opsForList().leftPop(key);
}
/**
* 移出并获取列表的第一个元素,如果列表没有元素会阻塞列表直到期待超时或发现可弹出元素为止
*
* @param key
* @param timeout 等待时间
* @param unit 工夫单位
* @return
*/
public String lBLeftPop(String key, long timeout, TimeUnit unit) {return redisTemplate.opsForList().leftPop(key, timeout, unit);
}
/**
* 移除并获取列表最初一个元素
*
* @param key
* @return 删除的元素
*/
public String lRightPop(String key) {return redisTemplate.opsForList().rightPop(key);
}
/**
* 移出并获取列表的最初一个元素,如果列表没有元素会阻塞列表直到期待超时或发现可弹出元素为止
*
* @param key
* @param timeout 等待时间
* @param unit 工夫单位
* @return
*/
public String lBRightPop(String key, long timeout, TimeUnit unit) {return redisTemplate.opsForList().rightPop(key, timeout, unit);
}
/**
* 移除列表的最初一个元素,并将该元素增加到另一个列表并返回
*
* @param sourceKey
* @param destinationKey
* @return
*/
public String lRightPopAndLeftPush(String sourceKey, String destinationKey) {return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
destinationKey);
}
/**
* 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它;如果列表没有元素会阻塞列表直到期待超时或发现可弹出元素为止
*
* @param sourceKey
* @param destinationKey
* @param timeout
* @param unit
* @return
*/
public String lBRightPopAndLeftPush(String sourceKey, String destinationKey,
long timeout, TimeUnit unit) {return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
destinationKey, timeout, unit);
}
/**
* 删除汇合中值等于 value 得元素
*
* @param key
* @param index index=0, 删除所有值等于 value 的元素; index>0, 从头部开始删除第一个值等于 value 的元素;
* index<0, 从尾部开始删除第一个值等于 value 的元素;
* @param value
* @return
*/
public Long lRemove(String key, long index, String value) {return redisTemplate.opsForList().remove(key, index, value);
}
/**
* 裁剪 list
*
* @param key
* @param start
* @param end
*/
public void lTrim(String key, long start, long end) {redisTemplate.opsForList().trim(key, start, end);
}
/**
* 获取列表长度
*
* @param key
* @return
*/
public Long lLen(String key) {return redisTemplate.opsForList().size(key);
}
/** --------------------set 相干操作 -------------------------- */
/**
* set 增加元素
*
* @param key
* @param values
* @return
*/
public Long sAdd(String key, String... values) {return redisTemplate.opsForSet().add(key, values);
}
/**
* set 移除元素
*
* @param key
* @param values
* @return
*/
public Long sRemove(String key, Object... values) {return redisTemplate.opsForSet().remove(key, values);
}
/**
* 移除并返回汇合的一个随机元素
*
* @param key
* @return
*/
public String sPop(String key) {return redisTemplate.opsForSet().pop(key);
}
/**
* 将元素 value 从一个汇合移到另一个汇合
*
* @param key
* @param value
* @param destKey
* @return
*/
public Boolean sMove(String key, String value, String destKey) {return redisTemplate.opsForSet().move(key, value, destKey);
}
/**
* 获取汇合的大小
*
* @param key
* @return
*/
public Long sSize(String key) {return redisTemplate.opsForSet().size(key);
}
/**
* 判断汇合是否蕴含 value
*
* @param key
* @param value
* @return
*/
public Boolean sIsMember(String key, Object value) {return redisTemplate.opsForSet().isMember(key, value);
}
/**
* 获取两个汇合的交加
*
* @param key
* @param otherKey
* @return
*/
public Set<String> sIntersect(String key, String otherKey) {return redisTemplate.opsForSet().intersect(key, otherKey);
}
/**
* 获取 key 汇合与多个汇合的交加
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sIntersect(String key, Collection<String> otherKeys) {return redisTemplate.opsForSet().intersect(key, otherKeys);
}
/**
* key 汇合与 otherKey 汇合的交加存储到 destKey 汇合中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long sIntersectAndStore(String key, String otherKey, String destKey) {return redisTemplate.opsForSet().intersectAndStore(key, otherKey,
destKey);
}
/**
* key 汇合与多个汇合的交加存储到 destKey 汇合中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long sIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {return redisTemplate.opsForSet().intersectAndStore(key, otherKeys,
destKey);
}
/**
* 获取两个汇合的并集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sUnion(String key, String otherKeys) {return redisTemplate.opsForSet().union(key, otherKeys);
}
/**
* 获取 key 汇合与多个汇合的并集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sUnion(String key, Collection<String> otherKeys) {return redisTemplate.opsForSet().union(key, otherKeys);
}
/**
* key 汇合与 otherKey 汇合的并集存储到 destKey 中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long sUnionAndStore(String key, String otherKey, String destKey) {return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
}
/**
* key 汇合与多个汇合的并集存储到 destKey 中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long sUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
}
/**
* 获取两个汇合的差集
*
* @param key
* @param otherKey
* @return
*/
public Set<String> sDifference(String key, String otherKey) {return redisTemplate.opsForSet().difference(key, otherKey);
}
/**
* 获取 key 汇合与多个汇合的差集
*
* @param key
* @param otherKeys
* @return
*/
public Set<String> sDifference(String key, Collection<String> otherKeys) {return redisTemplate.opsForSet().difference(key, otherKeys);
}
/**
* key 汇合与 otherKey 汇合的差集存储到 destKey 中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long sDifference(String key, String otherKey, String destKey) {return redisTemplate.opsForSet().differenceAndStore(key, otherKey,
destKey);
}
/**
* key 汇合与多个汇合的差集存储到 destKey 中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long sDifference(String key, Collection<String> otherKeys,
String destKey) {return redisTemplate.opsForSet().differenceAndStore(key, otherKeys,
destKey);
}
/**
* 获取汇合所有元素
*
* @param key
* @return
*/
public Set<String> setMembers(String key) {return redisTemplate.opsForSet().members(key);
}
/**
* 随机获取汇合中的一个元素
*
* @param key
* @return
*/
public String sRandomMember(String key) {return redisTemplate.opsForSet().randomMember(key);
}
/**
* 随机获取汇合中 count 个元素
*
* @param key
* @param count
* @return
*/
public List<String> sRandomMembers(String key, long count) {return redisTemplate.opsForSet().randomMembers(key, count);
}
/**
* 随机获取汇合中 count 个元素并且去除反复的
*
* @param key
* @param count
* @return
*/
public Set<String> sDistinctRandomMembers(String key, long count) {return redisTemplate.opsForSet().distinctRandomMembers(key, count);
}
/**
* @param key
* @param options
* @return
*/
public Cursor<String> sScan(String key, ScanOptions options) {return redisTemplate.opsForSet().scan(key, options);
}
/**------------------zSet 相干操作 --------------------------------*/
/**
* 增加元素, 有序汇合是依照元素的 score 值由小到大排列
*
* @param key
* @param value
* @param score
* @return
*/
public Boolean zAdd(String key, String value, double score) {return redisTemplate.opsForZSet().add(key, value, score);
}
/**
* @param key
* @param values
* @return
*/
public Long zAdd(String key, Set<ZSetOperations.TypedTuple<String>> values) {return redisTemplate.opsForZSet().add(key, values);
}
/**
* @param key
* @param values
* @return
*/
public Long zRemove(String key, Object... values) {return redisTemplate.opsForZSet().remove(key, values);
}
/**
* 减少元素的 score 值,并返回减少后的值
*
* @param key
* @param value
* @param delta
* @return
*/
public Double zIncrementScore(String key, String value, double delta) {return redisTemplate.opsForZSet().incrementScore(key, value, delta);
}
/**
* 返回元素在汇合的排名, 有序汇合是依照元素的 score 值由小到大排列
*
* @param key
* @param value
* @return 0 示意第一位
*/
public Long zRank(String key, Object value) {return redisTemplate.opsForZSet().rank(key, value);
}
/**
* 返回元素在汇合的排名, 按元素的 score 值由大到小排列
*
* @param key
* @param value
* @return
*/
public Long zReverseRank(String key, Object value) {return redisTemplate.opsForZSet().reverseRank(key, value);
}
/**
* 获取汇合的元素, 从小到大排序
*
* @param key
* @param start 开始地位
* @param end 完结地位, - 1 查问所有
* @return
*/
public Set<String> zRange(String key, long start, long end) {return redisTemplate.opsForZSet().range(key, start, end);
}
/**
* 获取汇合元素, 并且把 score 值也获取
*
* @param key
* @param start
* @param end
* @return
*/
public Set<ZSetOperations.TypedTuple<String>> zRangeWithScores(String key, long start,
long end) {return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
}
/**
* 依据 Score 值查问汇合元素
*
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public Set<String> zRangeByScore(String key, double min, double max) {return redisTemplate.opsForZSet().rangeByScore(key, min, max);
}
/**
* 依据 Score 值查问汇合元素, 从小到大排序
*
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
public Set<ZSetOperations.TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max) {return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
}
/**
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
public Set<ZSetOperations.TypedTuple<String>> zRangeByScoreWithScores(String key,
double min, double max, long start, long end) {return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
start, end);
}
/**
* 获取汇合的元素, 从大到小排序
*
* @param key
* @param start
* @param end
* @return
*/
public Set<String> zReverseRange(String key, long start, long end) {return redisTemplate.opsForZSet().reverseRange(key, start, end);
}
/**
* 获取汇合的元素, 从大到小排序, 并返回 score 值
*
* @param key
* @param start
* @param end
* @return
*/
public Set<ZSetOperations.TypedTuple<String>> zReverseRangeWithScores(String key,
long start, long end) {return redisTemplate.opsForZSet().reverseRangeWithScores(key, start,
end);
}
/**
* 依据 Score 值查问汇合元素, 从大到小排序
*
* @param key
* @param min
* @param max
* @return
*/
public Set<String> zReverseRangeByScore(String key, double min,
double max) {return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
}
/**
* 依据 Score 值查问汇合元素, 从大到小排序
*
* @param key
* @param min
* @param max
* @return
*/
public Set<ZSetOperations.TypedTuple<String>> zReverseRangeByScoreWithScores(String key, double min, double max) {return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
min, max);
}
/**
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
public Set<String> zReverseRangeByScore(String key, double min,
double max, long start, long end) {return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max,
start, end);
}
/**
* 依据 score 值获取汇合元素数量
*
* @param key
* @param min
* @param max
* @return
*/
public Long zCount(String key, double min, double max) {return redisTemplate.opsForZSet().count(key, min, max);
}
/**
* 获取汇合大小
*
* @param key
* @return
*/
public Long zSize(String key) {return redisTemplate.opsForZSet().size(key);
}
/**
* 获取汇合大小
*
* @param key
* @return
*/
public Long zZCard(String key) {return redisTemplate.opsForZSet().zCard(key);
}
/**
* 获取汇合中 value 元素的 score 值
*
* @param key
* @param value
* @return
*/
public Double zScore(String key, Object value) {return redisTemplate.opsForZSet().score(key, value);
}
/**
* 移除指定索引地位的成员
*
* @param key
* @param start
* @param end
* @return
*/
public Long zRemoveRange(String key, long start, long end) {return redisTemplate.opsForZSet().removeRange(key, start, end);
}
/**
* 依据指定的 score 值的范畴来移除成员
*
* @param key
* @param min
* @param max
* @return
*/
public Long zRemoveRangeByScore(String key, double min, double max) {return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
}
/**
* 获取 key 和 otherKey 的并集并存储在 destKey 中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long zUnionAndStore(String key, String otherKey, String destKey) {return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
}
/**
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long zUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {return redisTemplate.opsForZSet()
.unionAndStore(key, otherKeys, destKey);
}
/**
* 交加
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
public Long zIntersectAndStore(String key, String otherKey,
String destKey) {return redisTemplate.opsForZSet().intersectAndStore(key, otherKey,
destKey);
}
/**
* 交加
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Long zIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
destKey);
}
/**
* @param key
* @param options
* @return
*/
public Cursor<ZSetOperations.TypedTuple<String>> zScan(String key, ScanOptions options) {return redisTemplate.opsForZSet().scan(key, options);
}
}
package com.baba.security.common.utils;
import java.util.Random;
/**
* @Author wulongbo
* @Date 2021/10/25 15:54
* @Version 1.0
*/
public class SaltUtils {
/**
* 生成 salt 的静态方法
*/
public static String getSalt(int n) {char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+".toCharArray();
int length = chars.length;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {char achar = chars[new Random().nextInt(length)];
sb.append(achar);
}
return sb.toString();}
public static void main(String[] args) {System.out.println(getSalt(8));
}
}
package com.baba.security.common.utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @Author wulongbo
* @Date 2021/11/2 17:21
* @Version 1.0
*/
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
// 设置上下文
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {if (SpringUtils.applicationContext == null) {SpringUtils.applicationContext = applicationContext;}
}
// 获取上下文
public static ApplicationContext getApplicationContext() {return applicationContext;}
// 通过名字获取上下文的 Bean
public static Object getBean(String name) {return getApplicationContext().getBean(name);
}
// 通过类型获取上下文的 bean
public static <T> T getBean(Class<T> clazz) {return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {return getApplicationContext().getBean(name, clazz);
}
// 国际化应用
public static String getMessage(String key) {return applicationContext.getMessage(key, null, Locale.getDefault());
}
// 获取以后环境
public static String[] getActiveProfiles() {return applicationContext.getEnvironment().getActiveProfiles();}
// 判断以后环境是否为 test/local
public static boolean isDevEnv() {String[] activeProfiles = getActiveProfiles();
if (activeProfiles.length < 1) {return false;}
for (String activeProfile : activeProfiles) {if (StringUtils.equals(activeProfile, "dev")) {return true;}
}
return false;
}
}
-
VO 响应对象
package com.baba.security.common.vo; import com.baba.security.common.enums.ResultCode; import lombok.Data; /** * @Author wulongbo * @Date 2021/10/27 14:18 * @Version 1.0 */ @Data public class ResultVO<T> { /** * 状态码,比方 1000 代表响应胜利 */ private int code; /** * 响应信息,用来阐明响应状况 */ private String msg; /** * 响应的具体数据 */ private T data; public ResultVO(T data) {this(ResultCode.SUCCESS,data); } public ResultVO(ResultCode resultCode, T data) {this.code = resultCode.getCode(); this.msg = resultCode.getMessage(); this.data = data; } public ResultVO(ResultCode resultCode) {this.code = resultCode.getCode(); this.msg = resultCode.getMessage();} }
自此 common 模块就写实现,前面咱们来实现登录认证模块