自定义redis工具类,自定义Validator验证
1、自定义redis工具。
1.1 引入依赖 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> 1.2 配置application.yml redis: host: ****** //ip port: ****** //端口 timeout: 3 password: ****** //密码 poolMaxTotal: 10 poolMaxIdle: 10 poolMaxWait: 3 1.3 编写config类 @Component @ConfigurationProperties(prefix = "redis") @Data public class RedisConfig { private String host; private int port; private int timeout; private String password; private int poolMaxTotal; private int poolMaxIdle; private int poolMaxWait; } 1.4 创建RedisPoolFactory类 @Service public class RedisPoolFactory { @Autowired private RedisConfig redisConfig; @Bean public JedisPool jedisPoolFactory(){ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(redisConfig.getPoolMaxTotal()); jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle()); jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000); JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout() * 1000, redisConfig.getPassword(), 0); return jedisPool; } } 1.5 封装redis工具类 @Service public class RedisService { @Autowired private JedisPool jedisPool; /** 获取单个对象 */ public <T> T get(KeyPrefix prefix, String key, Class<T> clazz){ Jedis jedis = null; try{ jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; String str = jedis.get(realKey); T t = StringToBean(str, clazz); return t; }finally { returnToPool(jedis); } } /** 设置对象 */ public <T> boolean set(KeyPrefix prefix, String key, T value){ Jedis jedis = null; try{ jedis = jedisPool.getResource(); String str = beanToString(value); if(str == null || str.length() <= 0){ return false; } // 生成真正的key String realKey = prefix.getPrefix() + key; int seconds = prefix.expireSeconds(); if(seconds <= 0){ jedis.set(realKey, str); }else{ jedis.setex(realKey, seconds, str); } return true; }finally { returnToPool(jedis); } } /** 设置list集合 */ public <T> boolean setList(KeyPrefix prefix, String key, List<T> list){ Jedis jedis = null; try{ if(list != null && key != null && key != ""){ jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; int seconds = prefix.expireSeconds(); if(seconds <= 0){ jedis.set(realKey, JSON.toJSONString(list)); }else { jedis.setex(realKey, seconds, JSON.toJSONString(list)); } return true; } return false; }finally { returnToPool(jedis); } } /** 获取list集合 */ public <T> List<T> getList(KeyPrefix prefix, String key, Class<T> clazz){ Jedis jedis = null; try{ if(key != null && key != "" && clazz != null){ jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; List<T> list = JSONArray.parseArray(jedis.get(realKey), clazz); return list; } return null; }finally { returnToPool(jedis); } } /** 设置map集合 */ public boolean setMap(KeyPrefix prefix, String key, Map<String, Object> map){ Jedis jedis = null; try{ if(map != null && key != null && key != ""){ jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; int seconds = prefix.expireSeconds(); if(seconds <= 0){ jedis.set(realKey, JSON.toJSONString(map)); }else{ jedis.setex(realKey, seconds, JSON.toJSONString(map)); } return true; } return false; }finally { returnToPool(jedis); } } /** 获取map集合 */ public <T> Map<String, Object> getMap(KeyPrefix prefix, String key, Class<T> clazz){ Jedis jedis = null; try{ if(clazz != null && key != null && key != ""){ jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; Map<String, Object> map = JSONObject.toJavaObject(JSONObject.parseObject(jedis.get(realKey)), Map.class); return map; } return null; }finally { returnToPool(jedis); } } /** 判断key是否存在 */ public <T> boolean exists(KeyPrefix prefix, String key){ Jedis jedis = null; try{ jedis = jedisPool.getResource(); // 生成真的的key String realKey = prefix.getPrefix() + key; return jedis.exists(realKey); }finally { returnToPool(jedis); } } /** 删除 */ public <T> boolean delete(KeyPrefix prefix, String key){ Jedis jedis = null; try{ jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; long ret = jedis.del(realKey); return ret > 0; }finally { returnToPool(jedis); } } /** 增加值 */ public <T> Long incr(KeyPrefix prefix, String key){ Jedis jedis = null; try { jedis = jedisPool.getResource(); // 生成真的的key String realKey = prefix.getPrefix() + key; return jedis.incr(realKey); }finally { returnToPool(jedis); } } /** 减少值 */ public <T> Long decr(KeyPrefix prefix, String key){ Jedis jedis = null; try{ jedis = jedisPool.getResource(); //生成真正的key String realKey = prefix.getPrefix() + key; return jedis.decr(realKey); }finally { returnToPool(jedis); } } private <T> String beanToString(T value) { if(value == null){ return null; } Class<?> clazz = value.getClass(); if(clazz == int.class || clazz == Integer.class){ return "" + value; }else if(clazz == String.class){ return (String)value; }else if(clazz == long.class || clazz == Long.class){ return "" + value; }else{ return JSON.toJSONString(value); } } private <T> T StringToBean(String str, Class<T> clazz) { if(str == null || str.length() <= 0 || clazz == null){ return null; } if(clazz == int.class || clazz == Integer.class){ return (T)Integer.valueOf(str); }else if(clazz == String.class){ return (T)str; }else if(clazz == long.class || clazz == Long.class){ return (T)Long.valueOf(str); }else{ return JSON.toJavaObject(JSON.parseObject(str), clazz); } } private void returnToPool(Jedis jedis) { if(jedis != null){ jedis.close(); } } } 1.6 提供设置前缀和有效期的接口 public interface KeyPrefix { /** 有效期 */ public int expireSeconds(); /** 前缀 */ public String getPrefix(); } 1.7 实现设置前缀和有效期的类 public abstract class BasePrefix implements KeyPrefix { /** 过期时间 */ private int expireSeconds; /** 前缀 */ private String prefix; public BasePrefix(){ } /** 0代表永不过期 */ public BasePrefix(String prefix){ this(0, prefix); } public BasePrefix(int expireSeconds, String prefix){ this.expireSeconds = expireSeconds; this.prefix = prefix; } /** 默认0代表永不过期 */ @Override public int expireSeconds() { return expireSeconds; } @Override public String getPrefix() { String className = getClass().getSimpleName(); return className + "-" + prefix + "-"; } } 1.8 (实例)User模块引用 public class UserKey extends BasePrefix { private UserKey(String prefix) { super(prefix); } public static UserKey getById = new UserKey("id"); public static UserKey getByName = new UserKey("name"); public static UserKey getList = new UserKey("list"); public static UserKey getMap = new UserKey("map"); } 1.9 (实例)order模块引用 public class OrderKey extends BasePrefix { public static final int TOKEN_EXPIRE = 120; //秒 private OrderKey(int expireSeconds, String prefix) { super(expireSeconds, prefix); } public static OrderKey getToken = new OrderKey(TOKEN_EXPIRE, "token"); } ****demo(测试类) @Autowired private RedisService redisService; @GetMapping("/redisSet") @ResponseBody public Result redisSet(){ User user = new User(); user.setId(2); user.setName("222"); redisService.set(UserKey.getById, ""+ 1001, user); return Result.success(); } @GetMapping("/redisGet") @ResponseBody public Result redisGet(){ User user = (User) redisService.get(UserKey.getById, "" + 1001, User.class); return Result.success(); } @GetMapping("/redisDel") @ResponseBody public Result redisDel(){ redisService.delete(UserKey.getById, "" + 1001); return Result.success(); } @GetMapping("/setList") @ResponseBody public Result setList(){ User u1 = new User(1, "1001"); User u2 = new User(2, "1002"); User u3 = new User(3, "1003"); User u4 = new User(4, "1004"); List<User> userList = new ArrayList<>(); userList.add(u1); userList.add(u2); userList.add(u3); userList.add(u4); redisService.setList(UserKey.getList, "1001", userList); return Result.success(); } @GetMapping("/getList") @ResponseBody public Result getList(){ List<User> userList = redisService.getList(UserKey.getList, "1001", User.class); return Result.success(userList); } @GetMapping("/delList") @ResponseBody public Result delList(){ redisService.delete(UserKey.getList, "1001"); return Result.success(); } @GetMapping("/setMap") @ResponseBody public Result<Object> setMap(){ Map<String, Object> map = new HashMap<>(); map.put("a", "aaaa"); map.put("b", "bbbb"); map.put("c", "cccc"); map.put("d", "dddd"); redisService.setMap(UserKey.getMap, "a-d", map); return Result.success(); } @GetMapping("/getMap") @ResponseBody public Result getMap(){ Map<String, Object> map = redisService.getMap(UserKey.getMap, "a-d", Map.class); return Result.success(map); } @GetMapping("/delMap") @ResponseBody public Result delMap(){ redisService.delete(UserKey.getMap, "a-d"); return Result.success(); } @GetMapping("/setToken") @ResponseBody public Result setToken(){ redisService.set(OrderKey.getToken,"enheng", "enheng"); return Result.success(); } @GetMapping("/getToken") @ResponseBody public Result getToken(){ String token = redisService.get(OrderKey.getToken, "enheng", String.class); return Result.success(token); }
2、自定义Validator验证
2.1 引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> 2.2 实体类加注解 @Data public class LoginVO { @NotNull @IsMobile private String mobile; @NotNull @Length(min = 32) private String password; } 2.3 controller加注解 @PostMapping("/do_login") @ResponseBody public Result doLogin(@Valid LoginVO loginVO){ log.info(loginVO.toString()); //参数校验 /*if(StringUtils.isBlank(loginVO.getPassword())){ return Result.error(CodeMsg.PASSWORD_EMPTY); } if(StringUtils.isBlank(loginVO.getMobile())){ return Result.error(CodeMsg.MOBILE_EMPTY); } if(!ValidatorUtil.isMobileExact(loginVO.getMobile())){ return Result.error(CodeMsg.MOBILE_ERROR); }*/ //登录 seckillUserService.login(loginVO); return Result.success(true); } 2.4 自定参数校验器 /** * 自定义参数校验器 */ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint( validatedBy = {IsMobileValidator.class} ) public @interface IsMobile { boolean required() default true; String message() default "手机号码格式有误"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } 2.5实现 /** * 自定义参数校验器(实现) */ public class IsMobileValidator implements ConstraintValidator<IsMobile, String> { private boolean required = true; @Override public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.required(); } @Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { if(required){ return ValidatorUtil.isMobileExact(value); }else { if(StringUtils.isBlank(value)){ return true; }else { return ValidatorUtil.isMobileExact(value); } } } } 2.6定义全局异常处理器 @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public Result<String> exceptionHandler(HttpServletRequest request, Exception e){ if(e instanceof GlobalException){ GlobalException globalException = (GlobalException)e; return Result.error(globalException.getCodeMsg()); } else if(e instanceof BindException){ BindException bindException = (BindException)e; List<ObjectError> errors = bindException.getAllErrors(); ObjectError error = errors.get(0); String msg = error.getDefaultMessage(); return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg)); }else{ return Result.error(CodeMsg.SERVER_ERROR); } } } 2.7 定义异常使用类 @Getter public class GlobalException extends RuntimeException { private CodeMsg codeMsg; public GlobalException(CodeMsg codeMsg){ super(codeMsg.toString()); this.codeMsg = codeMsg; } } 2.8 全局返回类 @Getter @NoArgsConstructor @AllArgsConstructor public class Result<T> { private int code; private String msg; private T data; private Result(T data) { this.code = 0; this.msg = "success"; this.data = data; } private Result(CodeMsg codeMsg) { if (codeMsg == null){ return; } this.code = codeMsg.getCode(); this.msg = codeMsg.getMsg(); } /** 成功时调用(无参) */ public static <T> Result<T> success(){ return new Result<T>(CodeMsg.SUCCESS); } /** 成功时调用(有参) */ public static <T> Result<T> success(T data){ return new Result<T>(data); } /** 失败时调用(有参) */ public static <T> Result<T> error(CodeMsg codeMsg) { return new Result<T>(codeMsg); } } 2.9 全局错误码类 @Getter @NoArgsConstructor public class CodeMsg { private int code; private String msg; private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } public CodeMsg fillArgs(Object... args){ int code = this.code; String message = String.format(this.msg, args); return new CodeMsg(code, message); } //通用错误码 public static CodeMsg SUCCESS = new CodeMsg(0, "success"); public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常"); public static CodeMsg BIND_ERROR = new CodeMsg(500101, "参数校验异常: %s"); //登录模块 public static CodeMsg SESSION_ERROR = new CodeMsg(500210, "Session不存在或者已经失效"); public static CodeMsg PASSWORD_EMPTY = new CodeMsg(500211, "登录密码不能为空"); public static CodeMsg MOBILE_EMPTY = new CodeMsg(500212, "手机号不能为空"); public static CodeMsg MOBILE_ERROR = new CodeMsg(500213, "手机号格式错误"); public static CodeMsg MOBILE_NOT_EXIST = new CodeMsg(500214, "手机号不存在"); public static CodeMsg PASSWORD_ERROR = new CodeMsg(500215, "密码错误"); } ****demo public boolean login(LoginVO loginVO) { if(loginVO == null){ throw new GlobalException(CodeMsg.SERVER_ERROR); } //判断手机号是否存在 //log.info("手机号:{}", loginVO.getMobile()); //log.info("密码:{}", loginVO.getPassword()); SeckillUser seckillUser = getById(Long.parseLong(loginVO.getMobile())); if(seckillUser == null){ throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST); } //验证密码 String dbPass = seckillUser.getPassword(); String dbSalt = seckillUser.getSalt(); String calcPass = MD5Util.formPassToDBPass(loginVO.getPassword(), dbSalt); if(!dbPass.equals(calcPass)){ throw new GlobalException(CodeMsg.PASSWORD_ERROR); } return true; }

浙公网安备 33010602011771号