SpringBoot学习笔记

打印 上一主题 下一主题

主题 858|帖子 858|积分 2576

新建SpringBoot项目

阿里云地址:https://start.aliyun.com
异常消息处理
  1. // 1.自定义异常类,继承RuntimeException
  2. public class MyException extends RuntimeException{
  3.     public MyException() {
  4.     }
  5. }
  6. // 2.定义全局异常类
  7. @RestControllerAdvice
  8. public class GloabExceptionAdvice {
  9.     //异常注解,value是要拦截的异常类,可以自定义,这里为拦截整个异常类
  10.     @ExceptionHandler(value = Exception.class)
  11.     public ResponseEntity<Map<String,Object>> exceptionHandler(Exception ex) {
  12.         System.out.println("进入异常消息");
  13.         ex.printStackTrace();
  14.         return Result.res(HttpStatus.INTERNAL_SERVER_ERROR,false,ex.getMessage(),null,new Date());
  15.     }
  16. }
  17. // 3.主动抛出异常
  18. throw new MyException();
复制代码
异常处理类
  1. //作为springmvc的异常处理器
  2. //@ControllerAdvice
  3. @RestControllerAdvice
  4. public class ProjectExceptionAdvice {
  5.     @ExceptionHandler
  6.     public R doException(Exception ex) {
  7.         //to do
  8.         ex.printStackTrace();//控制台输出错误信息
  9.         return new R("服务器故障,请稍后再试!")
  10.     }
  11. }
复制代码
消息返回结果类
  1. public class R {
  2.     private Boolean flag;
  3.     private Object data;
  4.     private String msg;
  5.    
  6.     public R() {}
  7.    
  8.     public R(Boolean flag) {
  9.         this.flag = flag;
  10.     }
  11.    
  12.     public R(Boolean flag, Object data) {
  13.         this.flag = flag;
  14.         this.data = data;
  15.     }
  16.    
  17.     public R(String msg) {
  18.         this.msg = msg;
  19.     }
  20. }
复制代码
表现层统一api返回数据

status - int, 状态码
success - boolean, 结果标识,错误情况下需为 false
message - string, 错误信息
time - datetime, 当前时间
返回json数据
  1. {
  2.     "status": 200,
  3.     "success": true,
  4.     "message": "register successful",
  5.     "data": {
  6.         "nickname ": " Jones "
  7.         },
  8.     "time": "2021-08-23 14:50:28"
  9. }
复制代码
自定义返回数据类
  1. public class R {
  2.     private int status;
  3.     private Boolean success;
  4.     private Object data;
  5.     private String message;
  6.     private String time;
  7.    
  8.     public R() {}
  9.    
  10.     public R(Boolean success) {
  11.         this.success = success;
  12.     }
  13.    
  14.     public R(int status, Boolean success, String message, Object data, String time) {
  15.         this.status = status;
  16.         this.success = success;
  17.         this.message = message;
  18.         this.data = data;
  19.         this.time = time;
  20.     }
  21.    
  22.     public R(String message) {
  23.         this.success = false;
  24.         this.message = message;
  25.     }
  26. }
复制代码
基于ResponseEntity的自定义返回
  1. @Data
  2. public class Result{
  3.     private String aaaa;
  4.     public static ResponseEntity<Map<String,Object>> res(HttpStatus status, Boolean success, String message, Object data, Date time) {
  5.         Map<String,Object> map = new HashMap<>();
  6.         map.put("status",status.value());
  7.         map.put("success",success);
  8.         map.put("message",message);
  9.         map.put("data",data);
  10.         map.put("time",time);
  11.         return new ResponseEntity<>(map, status);
  12.     }
  13.     public static ResponseEntity<Map<String,Object>> res(Boolean success, String message, Object data, Date time) {
  14.         return res(HttpStatus.OK,success,message,data,time);
  15.     }
  16.     public static ResponseEntity<Map<String,Object>> res(Boolean success, String message, Object data) {
  17.         return res(HttpStatus.OK,success,message,data,new Date());
  18.     }
  19.     public static ResponseEntity<Map<String,Object>> res(String message, Object data) {
  20.         return res(HttpStatus.OK,true,message,data,new Date());
  21.     }
  22. }
复制代码
整合MyBatis

1、设置数据源参数
  1. spring:
  2.   datasource:
  3.     driver-class-name: com.mysql.cj.jdbc.Driver
  4.     url: jdbc:mysql://localhost:3306/databasename?serverTimezone=UTC
  5.     username: root
  6.     password: 123456
复制代码
2、定义数据层接口与映射配置
  1. @Mapper
  2. public interface UserDao {
  3.    
  4.     @Select("select * from user where id=#{id}")
  5.     public User getById(Integer id);
  6.    
  7.     @Select("select * from user")
  8.     public List<User> getAll();
  9. }
复制代码
3、XML配置
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5.    
  6. <mapper namespace="com.banyu.achieve.xml.dao.IUserDao">
  7.     <select id="findAll" resultType="com.banyu.achieve.xml.domain.User">
  8.         select * from user;
  9.     </select>
  10.     <insert id="saveUser" parameterType="com.banyu.achieve.xml.domain.User" >
  11.         
  12.         <selectKey keyColumn="id" resultType="int" order="AFTER" keyProperty="id">
  13.             select last_insert_id()
  14.         </selectKey>
  15.         insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
  16.     </insert>
  17.     <update id="updateUser" parameterType="com.banyu.achieve.xml.dao.IUserDao">
  18.         update user set username =#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id =#{id}
  19.     </update>
  20.     <select id="findUserByName" parameterType="String" resultType="user">
  21.         
  22.         
  23.         select * from user where username like "%${name}%"
  24.     </select>
  25.     <select id="getTotal" resultType="int" >
  26.         select count(*) from user
  27.     </select>
  28.     <delete id="deleteUser" parameterType="int">
  29.         delete from user where id = #{id}
  30.     </delete>
  31.         <select id="findUserById" parameterType="int" resultType="user">
  32.         select * from user where id = #{id}
  33.     </select>
  34. </mapper>
复制代码
Mybatis-plus

常用注解
  1. @TableName("表名")   //当表名与实体类名不一致时,可以在实体类上加入@TableName()声明
  2. @TableId(type =IdType.AUTO)  //设置为默认主键,方式为自增
  3. @TableId  //声明属性为表中的主键(若属性名称不为默认id)
  4. @TableFieId("字段")  //当实体类属性与表字段不一致时,可以用来声明
  5. @TableLogic   //指定逻辑删除字段
复制代码
自动填充
  1. //创建时间
  2. @TableField(fill = FieldFill.INSERT)
  3. private Date createTime;
  4. //更新时间
  5. @TableField(fill = FieldFill.INSERT_UPDATE)
  6. private Date updateTime;
复制代码
  1. @Component // 一定不要忘记把处理器加到IOC容器中!
  2. public class MyMetaObjectHandler implements MetaObjectHandler {
  3.     // 插入时的填充策略
  4.     @Override
  5.     public void insertFill(MetaObject metaObject) {
  6.         log.info("start insert fill.....");
  7.         // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
  8.         this.setFieldValByName("createTime",new Date(),metaObject);
  9.         this.setFieldValByName("updateTime",new Date(),metaObject);
  10.     }
  11.     // 更新时的填充策略
  12.     @Override
  13.     public void updateFill(MetaObject metaObject) {
  14.         log.info("start update fill.....");
  15.         this.setFieldValByName("updateTime",new Date(),metaObject);
  16.     }
  17. }
复制代码
查询

查询单个
  1. LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
  2. queryWrapper.eq(User::getUsername,user.getUsername());
  3. queryWrapper.eq(User::getPassword,user.getPassword());
  4. User userDB = userMapper.selectOne(queryWrapper);
  5. if (userDB!=null){
  6.     return userDB;
  7. }
  8. throw new RuntimeException("登录失败!!");
复制代码
查询多个
  1. userMapper.selectList(null);
复制代码
查询
  1. @Test
  2. public void testSelectById(){
  3.     User user =userMapper.selectById(1);
  4.     System.out.println(user)
  5. }
  6. //测试批量查询
  7. @Test
  8. public void testSelectByBatchId(){
  9.     List<User> user =userMapper.selectBatchIds(Arrays.asList(1,2,3));
  10.     users.forEach(System.out::println)
  11. }
  12. //条件查询
  13. public void testSelectByBatchIds(){
  14.     HashMap<String,Object> map=new HashMap<>();
  15.     //自定义查询
  16.     map.put("name","shuishui");
  17.     map.put("age",3);
  18.    
  19.     List<User> user = userMapper.selectByMap(map);
  20.     users.forEach(System.out::println);
  21. }
复制代码
分页

添加分页拦截器配置
  1. @Configuration
  2. public class MPConfig {
  3.     @Bean
  4.     public MybatisPlusInterceptor mybatisPlusInterceptor() {
  5.         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  6.         interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  7.         return interceptor;
  8.     }
  9. }
复制代码
分页功能实现
  1. @Test
  2. public void getByPage(current) {
  3.     //page对象
  4.     IPage page = new Page(1,5);
  5.     userMapper.selectPage(page,null);
  6.     System.out.println(page.getRecords());  //获取记录
  7. }
复制代码
JWT



JWT结构

1.Header
  1. {
  2.     "alg": "HS256",
  3.     "typ": "JWT"
  4. }
复制代码
2.Payload
  1. {
  2.     "name": "admin",
  3.     "admin": true
  4. }
复制代码
3.Signature

header和payload的base64编码加上密钥
  1. signature = HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload),secret)
复制代码
引入JWT


  • maven依赖
  1. <dependency>
  2.     <groupId>com.auth0</groupId>
  3.     <artifactId>java-jwt</artifactId>
  4.     <version>3.19.1</version>
  5. </dependency>
复制代码
Token生成
  1. public String getToken() {
  2.     //获取时间
  3.     Calendar instance = Calendar.getInstance();
  4.     instance.add(Calendar.SECOND,20);  //20秒
  5.     //生成token
  6.     String token = JWT.create()
  7.         .withClaim("userId", "1") //payload
  8.         .withClaim("username", "admin") //注意类型
  9.         .withExpiresAt(instance.getTime()) //令牌时间
  10.         .sign(Algorithm.HMAC256("123key"));//签名
  11.     System.out.println(token);
  12.     return token;
  13. }
复制代码
Token验证
  1. public Boolean verifyToken(){
  2.     //根据密钥构建验证
  3.     JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123key")).build();
  4.     try {
  5.         //验证token,如果验证失败则抛出异常
  6.         DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTExMjI3NTgsInVzZXJJZCI6IjEiLCJ1c2VybmFtZSI6ImFkbWluIn0.4aLHFDuJMJnFWali_3BSryE9ezdj6twj4QZnlwTVWDw");
  7.         //获取token里面的信息
  8.         System.out.println(verify.getClaim("userId").asString());
  9.         System.out.println(verify.getClaim("username").asString());
  10.     }catch (Exception e) {
  11.         //验证失败
  12.         e.printStackTrace();
  13.     }
  14. }
复制代码
Token异常处理

验证token失败的时候抛出的异常

  • 签名不一致异常
    SignatureVerificationException

  • 令牌过期异常
    TokenExpiredException

  • 算法不匹配异常
    AlgorithmMismatchException

  • 失效的payload异常
    InvalidClaimException

JWTUtil封装
  1. public class JWTUtil {
  2.     //signature密钥
  3.     private static final String SIGN = "123key";
  4.     /**
  5.      * 生成token
  6.      * @param map
  7.      * @return token
  8.      */
  9.     public static String getToken(Map<String,String> map){
  10.         //生成过期时间
  11.         Calendar instance = Calendar.getInstance();
  12.         instance.add(Calendar.DATE,7);
  13.         JWTCreator.Builder builder = JWT.create();
  14.         map.forEach(( k, v ) -> {
  15.             builder.withClaim(k,v);
  16.         });
  17.         String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));
  18.         return token;
  19.     }
  20.     /**
  21.      * 验证token并返回token的信息
  22.      * @param token
  23.      * @return token内信息
  24.      */
  25.     public static DecodedJWT verifyToken(String token) {
  26.         return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
  27.     }
  28. }
复制代码
Controller逻辑
  1. @RestController
  2. public class UserController {
  3.     @Autowired
  4.     private UserService userService;
  5.     @PostMapping("/user/login")
  6.     public ResponseEntity<Map<String,Object>> login(@RequestBody User user, HttpServletResponse response){
  7.         //返回数据的map
  8.         Map<String,Object> map = new HashMap<>();
  9.         //生成token用map
  10.         Map<String,String> payload = new HashMap<>();
  11.         try {
  12.             User userDB = userService.login(user);
  13.             //生成token
  14.             payload.put("userId", String.valueOf(userDB.getId()));
  15.             payload.put("username", userDB.getUsername());
  16.             String token = JWTUtil.getToken(payload);
  17.             map.put("state",true);
  18.             map.put("message","登录成功!!");
  19.             map.put("token",token);
  20.             //设置返回请求头
  21.             response.setHeader("token",token);
  22.         }catch (Exception e){
  23.             //            e.printStackTrace();
  24.             map.put("state",false);
  25.             map.put("message",e.getMessage());
  26.         }
  27.         return new ResponseEntity<>(map, HttpStatus.OK);
  28.     }
  29.     @PostMapping("/shop/test")
  30.     public ResponseEntity<Map<String,Object>> test() {
  31.         Map<String,Object> map = new HashMap<>();
  32.         map.put("state",true);
  33.         map.put("message","请求成功");
  34.         return new ResponseEntity<>(map,HttpStatus.OK);
  35.     }
  36. }
复制代码
Interceptor拦截器
  1. public class JWTInterceptor implements HandlerInterceptor {
  2.     @Override
  3.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  4.         Map<String,Object> map = new HashMap<>();
  5.         String token = request.getHeader("token");
  6.         try {
  7.             DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
  8.             return true; //正常返回true放行
  9.         }catch (SignatureVerificationException e){
  10.             e.printStackTrace();
  11.             map.put("message","无效签名");
  12.         }catch (TokenExpiredException e){
  13.             e.printStackTrace();
  14.             map.put("message","token过期");
  15.         }catch (AlgorithmMismatchException e){
  16.             e.printStackTrace();
  17.             map.put("message","token算法不一致");
  18.         }catch (Exception e){
  19.             e.printStackTrace();
  20.             map.put("message","无效签名");
  21.         }
  22.         map.put("state",false);
  23.         //jackson转换 map转json
  24.         String json = new ObjectMapper().writeValueAsString(map);
  25.         response.setContentType("application/json;charset=UTF-8"); //注意编码
  26.         response.getWriter().println(json);
  27.         return false; //拦截
  28.     }
  29. }
复制代码
配置添加拦截器
  1. @Configuration
  2. public class InterceptorConfig implements WebMvcConfigurer {
  3.     @Override
  4.     public void addInterceptors(InterceptorRegistry registry) {
  5.         //添加过滤规则
  6.         registry.addInterceptor(new JWTInterceptor())
  7.                 .addPathPatterns("/**") //所有路径都拦截
  8.                 .excludePathPatterns("/user/**"); //所有用户都放行
  9.     }
  10. }
复制代码
CORS跨域配置

全局配置
  1. @Configuration
  2. public class CorsConfig {
  3.     @Bean
  4.     public CorsFilter corsFilter() {
  5.         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  6.         CorsConfiguration corsConfiguration = new CorsConfiguration();
  7.         corsConfiguration.addAllowedOrigin("*"); //允许任何域名使用
  8.         corsConfiguration.addAllowedHeader("*"); //允许任何请求头
  9.         corsConfiguration.addAllowedMethod("*"); //允许任何请求方式
  10.         source.registerCorsConfiguration("/**",corsConfiguration); //处理所有请求的跨域配置
  11.         return new CorsFilter(source);
  12.     }
  13. }
复制代码
局部配置
  1. @CrossOrigin //直接加载controller上
  2. @Controller
复制代码
JJWT

安装maven依赖
  1. <dependency>
  2.     <groupId>io.jsonwebtoken</groupId>
  3.     <artifactId>jjwt</artifactId>
  4.     <version>0.9.1</version>
  5. </dependency>
复制代码
生成Token
  1. @Test
  2. void getToken() {
  3.     long time = 1000*60*60*24;  //过期时间
  4.     String sign = "123key";  //签名密钥
  5.     JwtBuilder jwtBuilder = Jwts.builder();  //jwt构造器
  6.     String jwtToken = jwtBuilder
  7.         .setHeaderParam("typ","JWT")  //设置header
  8.         .setHeaderParam("alg", "HS256")
  9.         .claim("username","tom")   //设置payload
  10.         .claim("role","admin")
  11.         .setSubject("admin-test")  //设置主题
  12.         .setExpiration(new Date(System.currentTimeMillis()+time))  //设置过期时间,当前系统时间加上24小时
  13.         .setId(UUID.randomUUID().toString())  //设置id
  14.         .signWith(SignatureAlgorithm.HS256,sign)  //签名,对应算法
  15.         .compact();  //组合前面的内容
  16.     System.out.println(jwtToken);
  17. }
复制代码
验证解析Token
  1. @Test
  2. public void parse() {
  3.     String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2NTE0MTg1MjQsImp0aSI6ImVhNTA1NjljLTYzYTYtNGEzZC1hNTc3LWI0NDViZDBmOTcwYiJ9.5dRw8edgag5dsRmTBr2XXaUC8RU6nypMBcqOd8ZcuJo";
  4.     String sign = "123key";
  5.     JwtParser jwtParser = Jwts.parser();
  6.     Jws<Claims> claimsJws = jwtParser.setSigningKey(sign).parseClaimsJws(token);
  7.     Claims claims = claimsJws.getBody();
  8.     System.out.println(claims.get("username"));
  9.     System.out.println(claims.get("role"));
  10.     System.out.println(claims.getSubject());
  11.     System.out.println(claims.getExpiration().toLocaleString());
  12. }
复制代码
自定义异常和404异常

自定义异常类
  1. package com.meteor.exception;
  2. //继承RuntimeException
  3. public class NotFoundException extends RuntimeException{
  4.     //继承父类的有参构造
  5.     public NotFoundException(String message) {
  6.         super(message);
  7.     }
  8. }
复制代码
全局异常拦截器
  1. @RestControllerAdvice
  2. public class GlobalExceptionResolver {
  3.     @ExceptionHandler(TokenExceptio.class)  //权限校验异常
  4.     public ResponseEntity<Map<String,Object>> tokenExceptionHandler(Exception ex) {
  5.         System.out.println("进入token权限校验异常");
  6.         Map<String,Object> map  = new HashMap<>();
  7.         map.put("message",ex.getMessage());
  8.         map.put("state",401);
  9.         return new ResponseEntity<>(map, HttpStatus.UNAUTHORIZED);
  10.     }
  11.     @ExceptionHandler(NotFoundException.class)  //404自定义异常
  12.     public ResponseEntity<String> notFoundExceptionHandler(Exception ex) {
  13.         System.out.println("进入资源未找到异常");
  14.         return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
  15.     }
  16.     @ExceptionHandler(Exception.class)  //用来处理所有异常
  17.     public ResponseEntity<String> exceptionHandler(Exception ex) {
  18.         System.out.println("进入自定义异常");
  19.         return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
  20.     }
  21. }
复制代码
权限拦截器
  1. //验证JWT,继承HandlerInterceptor
  2. public class JWTInterceptor implements HandlerInterceptor {
  3.     @Override
  4.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  5.         Map<String,Object> map = new HashMap<>();
  6.         String token = request.getHeader("token");
  7.         String msg = "";
  8.         try {
  9.             DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
  10.             return true;
  11.         }catch (SignatureVerificationException e){
  12.             e.printStackTrace();
  13.             msg = "无效签名"
  14.         }catch (TokenExpiredException e){
  15.             e.printStackTrace();
  16.             msg = "token过期"
  17.         }catch (AlgorithmMismatchException e){
  18.             e.printStackTrace();
  19.             msg = "token算法不一致"
  20.         }catch (Exception e){
  21.             e.printStackTrace();
  22.             msg = "无效签名"
  23.         }
  24.         throw new TokenExceptio(msg);  //直接抛出自定义异常
  25.     }
  26. }
复制代码
将拦截器添加到拦截器配置
  1. @Configuration
  2. public class InterceptorConfig implements WebMvcConfigurer {
  3.     @Override
  4.     public void addInterceptors(InterceptorRegistry registry) {
  5.         registry.addInterceptor(new JWTInterceptor())  //自定义拦截器
  6.                 .addPathPatterns("/**")  //添加拦截链接
  7.                 .excludePathPatterns("/user/**");   //添加排除链接
  8.     }
  9. }
复制代码
自定义错误异常控制器
  1. @RestController
  2. @RequestMapping({"${server.error.path:${error.path:/error}}"})
  3. public class MyErrorController implements ErrorController {
  4.     @RequestMapping
  5.     public ResponseEntity<Map<String,Object>> error(HttpServletRequest request) {
  6.         HttpStatus status = this.getStatus(request);
  7.         Map<String,Object> map = new HashMap<>();
  8.         map.put("status",status.value());
  9.         if (HttpStatus.NOT_FOUND.equals(status)) {
  10.             map.put("message","请求资源不存在");
  11.         } else if (HttpStatus.UNAUTHORIZED.equals(status)) {
  12.             map.put("message","账号权限不足");
  13.         }
  14.         return new ResponseEntity<>(map,HttpStatus.NOT_FOUND);
  15.     }
  16.     public HttpStatus getStatus(HttpServletRequest request) {
  17.         Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
  18.         System.out.println("权限state:" +  statusCode);
  19.         if (statusCode == null) {
  20.             return HttpStatus.INTERNAL_SERVER_ERROR;
  21.         } else {
  22.             try {
  23.                 return HttpStatus.valueOf(statusCode);
  24.             } catch (Exception var4) {
  25.                 return HttpStatus.INTERNAL_SERVER_ERROR;
  26.             }
  27.         }
  28.     }
  29. }
复制代码
hutool-all工具包

https://zhuanlan.zhihu.com/p/372359362
引入Hutool
  1. <dependency>
  2.     <groupId>cn.hutool</groupId>
  3.     <artifactId>hutool-all</artifactId>
  4.     <version>5.6.5</version>
  5. </dependency>
复制代码

Hibernate.validator

常用注解

注解释义@Nul被注释的元素必须为 null@NotNull被注释的元素必须不为 null@AssertTrue被注释的元素必须为 true@AssertFalse被注释的元素必须为 false@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@DecimalMax(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@Size(max, min)被注释的元素的大小必须在指定的范围内,元素必须为集合,代表集合个数@Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内@Past被注释的元素必须是一个过去的日期@Future被注释的元素必须是一个将来的日期@Email被注释的元素必须是电子邮箱地址@Length(min=, max=)被注释的字符串的大小必须在指定的范围内,必须为数组或者字符串,若微数组则表示为数组长度,字符串则表示为字符串长度@NotEmpty被注释的字符串的必须非空@Range(min=, max=)被注释的元素必须在合适的范围内@NotBlank被注释的字符串的必须非空@Pattern(regexp = )正则表达式校验@Valid对象级联校验,即校验对象中对象的属性使用步骤

1、在Employee类上加上具体的约束注解。
  1. public class Employee {
  2.    @Null
  3.    private Integer id;
  4.    
  5.    @NotNull
  6.    private Integer parent_id;
  7.    
  8.    @NotBlank
  9.    private String name;
  10.    @PastOrPresent
  11.    private LocalDateTime createtime;
  12. }
复制代码
2、在controller的类上加上@Validated注解,标注这个类需要校验。在需要校验的参数前面加上@Valid注解,使这个实体类的属性得到校验。
  1. @RestController
  2. @Validated
  3. public class TestController2 {
  4.     @PostMapping("/add")
  5.     public Object add(@RequestBody @Valid Employee employee){
  6.         return "ok";
  7.     }
  8. }
复制代码
3、Validator的全局异常捕获
  1. @RestControllerAdvice
  2. public class GlobalExceptionHandler {
  3.     @ExceptionHandler(value = {VerifyEXception.class, MethodArgumentNotValidException.class})
  4.     public ResponseEntity<Map<String,Object>> verifyEceptionHandler(Exception ex) {
  5.         System.out.println("进入数据校验失败异常");
  6.         //获取valid的message
  7.         String msg = ((MethodArgumentNotValidException) ex).getFieldError().getDefaultMessage();
  8.         return Result.res(HttpStatus.UNPROCESSABLE_ENTITY,false,msg,null,new Date());
  9.     }
  10. }
  11. @ExceptionHandler(MethodArgumentNotValidException.class)
  12. @ResponseBody
  13. public ResponseEntity handleBindException(MethodArgumentNotValidException ex) {
  14.     FieldError fieldError = ex.getBindingResult().getFieldError();
  15.     log.warn("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
  16.     return ResponseEntity.ok(Response.fail(211,fieldError.getDefaultMessage(),fieldError.getDefaultMessage()));
  17. }
复制代码
Get请求
  1. @RestController
  2. @RequestMapping("/test")
  3. @Validated
  4. public class TestController {
  5.     /**
  6.      * 测试校验框架返回结果格式
  7.      */
  8.     @GetMapping(value = "/validator2")
  9.     public String testValidator2(@NotBlank(message = "姓名不能为空") String name){
  10.         return "校验成功...";
  11.     }
  12. }
复制代码
Annotation

权限注解,用于Contoller方法上,在拦截器preHandle中进行权限校验,原理是获取方法上的权限注解,根据注解的值进行校验。
  1. @Target(ElementType.METHOD)                                // 该注解可作用的目标
  2. @Retention(RetentionPolicy.RUNTIME)                // 作用时机
  3. public @interface AuthCheck {
  4.     String value() default "";  // 默认为空
  5. }
复制代码
校验注解
  1. private Optional<AuthCheck> getAuthCheck(Object handler) {
  2.     if (handler instanceof HandlerMethod) {
  3.         HandlerMethod handlerMethod = (HandlerMethod) handler;
  4.         AuthCheck authCheck = handlerMethod.getMethod().getAnnotation(AuthCheck.class);
  5.         if (authCheck == null) {
  6.             return Optional.empty();
  7.         }
  8.         return Optional.of(authCheck);
  9.     }
  10.     return Optional.empty();
  11. }
复制代码
调用方法
  1. Optional<AuthCheck> authCheck = this.getAuthCheck(handler);
  2. if (!authCheck.isPresent()) {
  3.     return true;
  4. }
复制代码
ThreadLocal

一、ThreadLocal简介

多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线程安全性。ThreadLocal是除了加锁这种同步方式之外的一种保证一种规避多线程访问出现线程不安全的方法,当我们在创建一个变量后,如果每个线程对其进行访问的时候访问的都是线程自己的变量这样就不会存在线程不安全问题。
  ThreadLocal是JDK包提供的,它提供线程本地变量,如果创建一乐ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的一个副本,在实际多线程操作的时候,操作的是自己本地内存中的变量,从而规避了线程安全问题,如下图所示:

ThreadLocal常用方法:

  • public void set(T value)       设置当前线程的线程句不变量的值
  • public T get()                       返回当前线程所对应的线程局部变量的值
二、Springboot应用ThreadLocal

使用ThreadLocal保存用户信息
客户端发送的每次Http请求,对应的在服务端都会分配一个新的线程来处理,在处理过程中设计到的后端代码都属于同一个线程,可以通过一下代码获取线程ID.
  1. Thread.currentThread().getId();  //获取当前线程ID
复制代码
我们可以配置拦截器,通过preHandle方法中的header来获取User信息,并调用ThreadLocal的set方法来设置当前线程的线程局部变量的值(用户信息User),然后就能在后续的Controller方法中通过ThreadLocal的get方法来获取到用户信息(可实现权限控制)
编写User实体类
  1. @Data
  2. public class User() {
  3.     private Long id;
  4.     private String username;
  5.     private String password;
  6.     private Integer type;     //用户类型,用于权限校验
  7. }
复制代码
编写AuthUser类,封装ThreadLocal来操作用户数据
  1. public class AuthUser {
  2.     private static final ThreadLocal<User> threadLocal = new ThreadLocal() ;
  3.     public static User get() {
  4.         return threadLocal.get();
  5.     }
  6.     public static void set(User value) {
  7.         threadLocal.set(value);
  8.     }
  9.     public static void remove() {
  10.         threadLocal.remove();
  11.     }
  12.     public static Long getUserId() {
  13.         try {
  14.             return threadLocal.get().getUid();
  15.         } catch (Exception e) {
  16.             throw new TokenCheckException("铁子,请先登录再操作");
  17.         }
  18.     }
  19. }
复制代码
Redis

基本操作
  1. //增
  2. redisTemplate.opsForValue().put("key","value");
  3. //删
  4. redisTemplate.delete(key);
  5. //改
  6. redisTemplate.opsForValue().set("key","value");
  7. //查
  8. redisTemplate.opsForValue().get("key");
  9. //是否存在
  10. redisTemplate.hasKey(key);
  11. //设置过期时间
  12. redisTemplate.expire(key, timeout, unit);
  13. redisTemplate.expireAt(key, date);
复制代码
使用redis实现登录

登录成功将用户信息存入redis
redis工具类
  1. @Component
  2. @SuppressWarnings({"unchecked", "all"})
  3. public class RedisUtils {
  4.     private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
  5.     private RedisTemplate<String, String> redisTemplate;
  6.     public RedisUtils(RedisTemplate<String, String> redisTemplate) {
  7.         this.redisTemplate = redisTemplate;
  8.     }
  9.     /**
  10.      * 指定缓存失效时间
  11.      *
  12.      * @param key  键
  13.      * @param time 时间(秒)
  14.      */
  15.     public boolean expire(String key, long time) {
  16.         try {
  17.             if (time > 0) {
  18.                 redisTemplate.expire(key, time, TimeUnit.SECONDS);
  19.             }
  20.         } catch (Exception e) {
  21.             log.error(e.getMessage(), e);
  22.             return false;
  23.         }
  24.         return true;
  25.     }
  26.     /**
  27.      * 指定缓存失效时间
  28.      *
  29.      * @param key      键
  30.      * @param time     时间(秒)
  31.      * @param timeUnit 单位
  32.      */
  33.     public boolean expire(String key, long time, TimeUnit timeUnit) {
  34.         try {
  35.             if (time > 0) {
  36.                 redisTemplate.expire(key, time, timeUnit);
  37.             }
  38.         } catch (Exception e) {
  39.             log.error(e.getMessage(), e);
  40.             return false;
  41.         }
  42.         return true;
  43.     }
  44.     /**
  45.      * 根据 key 获取过期时间
  46.      *
  47.      * @param key 键 不能为null
  48.      * @return 时间(秒) 返回0代表为永久有效
  49.      */
  50.     public long getExpire(String key) {
  51.         return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  52.     }
  53.     /**
  54.      * 查找匹配key
  55.      *
  56.      * @param pattern key
  57.      * @return /
  58.      */
  59.     public List<String> scan(String pattern) {
  60.         ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
  61.         RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
  62.         RedisConnection rc = Objects.requireNonNull(factory).getConnection();
  63.         Cursor<byte[]> cursor = rc.scan(options);
  64.         List<String> result = new ArrayList<>();
  65.         while (cursor.hasNext()) {
  66.             result.add(new String(cursor.next()));
  67.         }
  68.         try {
  69.             RedisConnectionUtils.releaseConnection(rc, factory);
  70.         } catch (Exception e) {
  71.             log.error(e.getMessage(), e);
  72.         }
  73.         return result;
  74.     }
  75.     /**
  76.      * 分页查询 key
  77.      *
  78.      * @param patternKey key
  79.      * @param page       页码
  80.      * @param size       每页数目
  81.      * @return /
  82.      */
  83.     public List<String> findKeysForPage(String patternKey, int page, int size) {
  84.         ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
  85.         RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
  86.         RedisConnection rc = Objects.requireNonNull(factory).getConnection();
  87.         Cursor<byte[]> cursor = rc.scan(options);
  88.         List<String> result = new ArrayList<>(size);
  89.         int tmpIndex = 0;
  90.         int fromIndex = page * size;
  91.         int toIndex = page * size + size;
  92.         while (cursor.hasNext()) {
  93.             if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
  94.                 result.add(new String(cursor.next()));
  95.                 tmpIndex++;
  96.                 continue;
  97.             }
  98.             // 获取到满足条件的数据后,就可以退出了
  99.             if (tmpIndex >= toIndex) {
  100.                 break;
  101.             }
  102.             tmpIndex++;
  103.             cursor.next();
  104.         }
  105.         try {
  106.             RedisConnectionUtils.releaseConnection(rc, factory);
  107.         } catch (Exception e) {
  108.             log.error(e.getMessage(), e);
  109.         }
  110.         return result;
  111.     }
  112.     /**
  113.      * 判断key是否存在
  114.      *
  115.      * @param key 键
  116.      * @return true 存在 false不存在
  117.      */
  118.     public boolean hasKey(String key) {
  119.         try {
  120.             return redisTemplate.hasKey(key);
  121.         } catch (Exception e) {
  122.             log.error(e.getMessage(), e);
  123.             return false;
  124.         }
  125.     }
  126.     /**
  127.      * 删除缓存
  128.      *
  129.      * @param key 可以传一个值 或多个
  130.      */
  131.     public void del(String... keys) {
  132.         if (keys != null && keys.length > 0) {
  133.             if (keys.length == 1) {
  134.                 boolean result = redisTemplate.delete(keys[0]);
  135.                 log.debug("--------------------------------------------");
  136.                 log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString());
  137.                 log.debug("--------------------------------------------");
  138.             } else {
  139.                 Set<String> keySet = new HashSet<>();
  140.                 for (String key : keys) {
  141.                     keySet.addAll(redisTemplate.keys(key));
  142.                 }
  143.                 long count = redisTemplate.delete(keySet);
  144.                 log.debug("--------------------------------------------");
  145.                 log.debug("成功删除缓存:" + keySet.toString());
  146.                 log.debug("缓存删除数量:" + count + "个");
  147.                 log.debug("--------------------------------------------");
  148.             }
  149.         }
  150.     }
  151.     // ============================String=============================
  152.     /**
  153.      * 普通缓存获取
  154.      *
  155.      * @param key 键
  156.      * @return 值
  157.      */
  158.     public String get(String key) {
  159.         return key == null ? null : redisTemplate.opsForValue().get(key);
  160.     }
  161.     /**
  162.      * 批量获取
  163.      *
  164.      * @param keys
  165.      * @return
  166.      */
  167.     public List<Object> multiGet(List<String> keys) {
  168.         List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys));
  169.         List resultList = Lists.newArrayList();
  170.         Optional.ofNullable(list).ifPresent(e-> list.forEach(ele-> Optional.ofNullable(ele).ifPresent(resultList::add)));
  171.         return resultList;
  172.     }
  173.     /**
  174.      * 普通缓存放入
  175.      *
  176.      * @param key   键
  177.      * @param value 值
  178.      * @return true成功 false失败
  179.      */
  180.     public boolean set(String key, String value) {
  181.         try {
  182.             redisTemplate.opsForValue().set(key, value);
  183.             return true;
  184.         } catch (Exception e) {
  185.             log.error(e.getMessage(), e);
  186.             return false;
  187.         }
  188.     }
  189.     /**
  190.      * 普通缓存放入并设置时间
  191.      *
  192.      * @param key   键
  193.      * @param value 值
  194.      * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
  195.      * @return true成功 false 失败
  196.      */
  197.     public boolean set(String key, String value, long time) {
  198.         try {
  199.             if (time > 0) {
  200.                 redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  201.             } else {
  202.                 set(key, value);
  203.             }
  204.             return true;
  205.         } catch (Exception e) {
  206.             log.error(e.getMessage(), e);
  207.             return false;
  208.         }
  209.     }
  210.     /**
  211.      * 普通缓存放入并设置时间
  212.      *
  213.      * @param key      键
  214.      * @param value    值
  215.      * @param time     时间
  216.      * @param timeUnit 类型
  217.      * @return true成功 false 失败
  218.      */
  219.     public boolean set(String key, String value, long time, TimeUnit timeUnit) {
  220.         try {
  221.             if (time > 0) {
  222.                 redisTemplate.opsForValue().set(key, value, time, timeUnit);
  223.             } else {
  224.                 set(key, value);
  225.             }
  226.             return true;
  227.         } catch (Exception e) {
  228.             log.error(e.getMessage(), e);
  229.             return false;
  230.         }
  231.     }
  232.     // ================================Map=================================
  233.     /**
  234.      * HashGet
  235.      *
  236.      * @param key  键 不能为null
  237.      * @param item 项 不能为null
  238.      * @return 值
  239.      */
  240.     public Object hget(String key, String item) {
  241.         return redisTemplate.opsForHash().get(key, item);
  242.     }
  243.     /**
  244.      * 获取hashKey对应的所有键值
  245.      *
  246.      * @param key 键
  247.      * @return 对应的多个键值
  248.      */
  249.     public Map<Object, Object> hmget(String key) {
  250.         return redisTemplate.opsForHash().entries(key);
  251.     }
  252.     /**
  253.      * HashSet
  254.      *
  255.      * @param key 键
  256.      * @param map 对应多个键值
  257.      * @return true 成功 false 失败
  258.      */
  259.     public boolean hmset(String key, Map<String, Object> map) {
  260.         try {
  261.             redisTemplate.opsForHash().putAll(key, map);
  262.             return true;
  263.         } catch (Exception e) {
  264.             log.error(e.getMessage(), e);
  265.             return false;
  266.         }
  267.     }
  268.     /**
  269.      * HashSet 并设置时间
  270.      *
  271.      * @param key  键
  272.      * @param map  对应多个键值
  273.      * @param time 时间(秒)
  274.      * @return true成功 false失败
  275.      */
  276.     public boolean hmset(String key, Map<String, Object> map, long time) {
  277.         try {
  278.             redisTemplate.opsForHash().putAll(key, map);
  279.             if (time > 0) {
  280.                 expire(key, time);
  281.             }
  282.             return true;
  283.         } catch (Exception e) {
  284.             log.error(e.getMessage(), e);
  285.             return false;
  286.         }
  287.     }
  288.     /**
  289.      * 向一张hash表中放入数据,如果不存在将创建
  290.      *
  291.      * @param key   键
  292.      * @param item  项
  293.      * @param value 值
  294.      * @return true 成功 false失败
  295.      */
  296.     public boolean hset(String key, String item, String value) {
  297.         try {
  298.             redisTemplate.opsForHash().put(key, item, value);
  299.             return true;
  300.         } catch (Exception e) {
  301.             log.error(e.getMessage(), e);
  302.             return false;
  303.         }
  304.     }
  305.     /**
  306.      * 向一张hash表中放入数据,如果不存在将创建
  307.      *
  308.      * @param key   键
  309.      * @param item  项
  310.      * @param value 值
  311.      * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  312.      * @return true 成功 false失败
  313.      */
  314.     public boolean hset(String key, String item, String value, long time) {
  315.         try {
  316.             redisTemplate.opsForHash().put(key, item, value);
  317.             if (time > 0) {
  318.                 expire(key, time);
  319.             }
  320.             return true;
  321.         } catch (Exception e) {
  322.             log.error(e.getMessage(), e);
  323.             return false;
  324.         }
  325.     }
  326.     /**
  327.      * 删除hash表中的值
  328.      *
  329.      * @param key  键 不能为null
  330.      * @param item 项 可以使多个 不能为null
  331.      */
  332.     public void hdel(String key, String... item) {
  333.         redisTemplate.opsForHash().delete(key, item);
  334.     }
  335.     /**
  336.      * 判断hash表中是否有该项的值
  337.      *
  338.      * @param key  键 不能为null
  339.      * @param item 项 不能为null
  340.      * @return true 存在 false不存在
  341.      */
  342.     public boolean hHasKey(String key, String item) {
  343.         return redisTemplate.opsForHash().hasKey(key, item);
  344.     }
  345.     /**
  346.      * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  347.      *
  348.      * @param key  键
  349.      * @param item 项
  350.      * @param by   要增加几(大于0)
  351.      * @return
  352.      */
  353.     public double hincr(String key, String item, double by) {
  354.         return redisTemplate.opsForHash().increment(key, item, by);
  355.     }
  356.     /**
  357.      * hash递减
  358.      *
  359.      * @param key  键
  360.      * @param item 项
  361.      * @param by   要减少记(小于0)
  362.      * @return
  363.      */
  364.     public double hdecr(String key, String item, double by) {
  365.         return redisTemplate.opsForHash().increment(key, item, -by);
  366.     }
  367.     // ============================set=============================
  368.     /**
  369.      * 根据key获取Set中的所有值
  370.      *
  371.      * @param key 键
  372.      * @return
  373.      */
  374.     public Set<String> sGet(String key) {
  375.         try {
  376.             return redisTemplate.opsForSet().members(key);
  377.         } catch (Exception e) {
  378.             log.error(e.getMessage(), e);
  379.             return null;
  380.         }
  381.     }
  382.     /**
  383.      * 根据value从一个set中查询,是否存在
  384.      *
  385.      * @param key   键
  386.      * @param value 值
  387.      * @return true 存在 false不存在
  388.      */
  389.     public boolean sHasKey(String key, String value) {
  390.         try {
  391.             return redisTemplate.opsForSet().isMember(key, value);
  392.         } catch (Exception e) {
  393.             log.error(e.getMessage(), e);
  394.             return false;
  395.         }
  396.     }
  397.     /**
  398.      * 将数据放入set缓存
  399.      *
  400.      * @param key    键
  401.      * @param values 值 可以是多个
  402.      * @return 成功个数
  403.      */
  404.     public long sSet(String key, String... values) {
  405.         try {
  406.             return redisTemplate.opsForSet().add(key, values);
  407.         } catch (Exception e) {
  408.             log.error(e.getMessage(), e);
  409.             return 0;
  410.         }
  411.     }
  412.     /**
  413.      * 将set数据放入缓存
  414.      *
  415.      * @param key    键
  416.      * @param time   时间(秒)
  417.      * @param values 值 可以是多个
  418.      * @return 成功个数
  419.      */
  420.     public long sSetAndTime(String key, long time, String... values) {
  421.         try {
  422.             Long count = redisTemplate.opsForSet().add(key, values);
  423.             if (time > 0) {
  424.                 expire(key, time);
  425.             }
  426.             return count;
  427.         } catch (Exception e) {
  428.             log.error(e.getMessage(), e);
  429.             return 0;
  430.         }
  431.     }
  432.     /**
  433.      * 获取set缓存的长度
  434.      *
  435.      * @param key 键
  436.      * @return
  437.      */
  438.     public long sGetSetSize(String key) {
  439.         try {
  440.             return redisTemplate.opsForSet().size(key);
  441.         } catch (Exception e) {
  442.             log.error(e.getMessage(), e);
  443.             return 0;
  444.         }
  445.     }
  446.     /**
  447.      * 移除值为value的
  448.      *
  449.      * @param key    键
  450.      * @param values 值 可以是多个
  451.      * @return 移除的个数
  452.      */
  453.     public long setRemove(String key, Object... values) {
  454.         try {
  455.             Long count = redisTemplate.opsForSet().remove(key, values);
  456.             return count;
  457.         } catch (Exception e) {
  458.             log.error(e.getMessage(), e);
  459.             return 0;
  460.         }
  461.     }
  462.     // ===============================list=================================
  463.     /**
  464.      * 获取list缓存的内容
  465.      *
  466.      * @param key   键
  467.      * @param start 开始
  468.      * @param end   结束 0 到 -1代表所有值
  469.      * @return
  470.      */
  471.     public List<String> lGet(String key, long start, long end) {
  472.         try {
  473.             return redisTemplate.opsForList().range(key, start, end);
  474.         } catch (Exception e) {
  475.             log.error(e.getMessage(), e);
  476.             return null;
  477.         }
  478.     }
  479.     /**
  480.      * 获取list缓存的长度
  481.      *
  482.      * @param key 键
  483.      * @return
  484.      */
  485.     public long lGetListSize(String key) {
  486.         try {
  487.             return redisTemplate.opsForList().size(key);
  488.         } catch (Exception e) {
  489.             log.error(e.getMessage(), e);
  490.             return 0;
  491.         }
  492.     }
  493.     /**
  494.      * 通过索引 获取list中的值
  495.      *
  496.      * @param key   键
  497.      * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  498.      * @return
  499.      */
  500.     public Object lGetIndex(String key, long index) {
  501.         try {
  502.             return redisTemplate.opsForList().index(key, index);
  503.         } catch (Exception e) {
  504.             log.error(e.getMessage(), e);
  505.             return null;
  506.         }
  507.     }
  508.     /**
  509.      * 将list放入缓存
  510.      *
  511.      * @param key   键
  512.      * @param value 值
  513.      * @return
  514.      */
  515.     public boolean lSet(String key, String value) {
  516.         try {
  517.             redisTemplate.opsForList().rightPush(key, value);
  518.             return true;
  519.         } catch (Exception e) {
  520.             log.error(e.getMessage(), e);
  521.             return false;
  522.         }
  523.     }
  524.     /**
  525.      * 将list放入缓存
  526.      *
  527.      * @param key   键
  528.      * @param value 值
  529.      * @param time  时间(秒)
  530.      * @return
  531.      */
  532.     public boolean lSet(String key, String value, long time) {
  533.         try {
  534.             redisTemplate.opsForList().rightPush(key, value);
  535.             if (time > 0) {
  536.                 expire(key, time);
  537.             }
  538.             return true;
  539.         } catch (Exception e) {
  540.             log.error(e.getMessage(), e);
  541.             return false;
  542.         }
  543.     }
  544.     /**
  545.      * 将list放入缓存
  546.      *
  547.      * @param key   键
  548.      * @param value 值
  549.      * @return
  550.      */
  551.     public boolean lSet(String key, List<String> value) {
  552.         try {
  553.             redisTemplate.opsForList().rightPushAll(key, value);
  554.             return true;
  555.         } catch (Exception e) {
  556.             log.error(e.getMessage(), e);
  557.             return false;
  558.         }
  559.     }
  560.     /**
  561.      * 将list放入缓存
  562.      *
  563.      * @param key   键
  564.      * @param value 值
  565.      * @param time  时间(秒)
  566.      * @return
  567.      */
  568.     public boolean lSet(String key, List<String> value, long time) {
  569.         try {
  570.             redisTemplate.opsForList().rightPushAll(key, value);
  571.             if (time > 0) {
  572.                 expire(key, time);
  573.             }
  574.             return true;
  575.         } catch (Exception e) {
  576.             log.error(e.getMessage(), e);
  577.             return false;
  578.         }
  579.     }
  580.     /**
  581.      * 根据索引修改list中的某条数据
  582.      *
  583.      * @param key   键
  584.      * @param index 索引
  585.      * @param value 值
  586.      * @return /
  587.      */
  588.     public boolean lUpdateIndex(String key, long index, String value) {
  589.         try {
  590.             redisTemplate.opsForList().set(key, index, value);
  591.             return true;
  592.         } catch (Exception e) {
  593.             log.error(e.getMessage(), e);
  594.             return false;
  595.         }
  596.     }
  597.     /**
  598.      * 移除N个值为value
  599.      *
  600.      * @param key   键
  601.      * @param count 移除多少个
  602.      * @param value 值
  603.      * @return 移除的个数
  604.      */
  605.     public long lRemove(String key, long count, Object value) {
  606.         try {
  607.             return redisTemplate.opsForList().remove(key, count, value);
  608.         } catch (Exception e) {
  609.             log.error(e.getMessage(), e);
  610.             return 0;
  611.         }
  612.     }
  613.     /**
  614.      * @param prefix 前缀
  615.      * @param ids    id
  616.      */
  617.     public void delByKeys(String prefix, Set<Long> ids) {
  618.         Set<String> keys = new HashSet<>();
  619.         for (Long id : ids) {
  620.             keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString()));
  621.         }
  622.         long count = redisTemplate.delete(keys);
  623.         // 此处提示可自行删除
  624.         log.debug("--------------------------------------------");
  625.         log.debug("成功删除缓存:" + keys.toString());
  626.         log.debug("缓存删除数量:" + count + "个");
  627.         log.debug("--------------------------------------------");
  628.     }
  629. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

祗疼妳一个

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表