diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java index b32e64d7..09a50417 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java @@ -16,7 +16,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { public static List toPage(int page, int size , List list) { int fromIndex = page * size; int toIndex = page * size + size; - if(fromIndex > list.size()){ return new ArrayList(); } else if(toIndex >= list.size()) { @@ -43,7 +42,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { Map map = new LinkedHashMap<>(2); map.put("content",object); map.put("totalElements",totalElements); - return map; } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/RedisUtils.java b/eladmin-common/src/main/java/me/zhengjie/utils/RedisUtils.java new file mode 100644 index 00000000..28651fa2 --- /dev/null +++ b/eladmin-common/src/main/java/me/zhengjie/utils/RedisUtils.java @@ -0,0 +1,615 @@ +package me.zhengjie.utils; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.*; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * @author / + */ +@Component +@SuppressWarnings({"unchecked","all"}) +public class RedisUtils { + + private RedisTemplate redisTemplate; + @Value("${jwt.online-key}") + private String onlineKey; + + public RedisUtils(RedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + // =============================common============================ + + /** + * 指定缓存失效时间 + * @param key 键 + * @param time 时间(秒) + */ + public boolean expire(String key, long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 根据 key 获取过期时间 + * @param key 键 不能为null + * @return 时间(秒) 返回0代表为永久有效 + */ + public long getExpire(Object key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + /** + * 查找匹配key + * @param pattern key + * @return / + */ + public List scan(String pattern) { + ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); + RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); + RedisConnection rc = Objects.requireNonNull(factory).getConnection(); + Cursor cursor = rc.scan(options); + List result = new ArrayList<>(); + while (cursor.hasNext()) { + result.add(new String(cursor.next())); + } + try { + RedisConnectionUtils.releaseConnection(rc, factory); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 分页查询 key + * @param patternKey key + * @param page 页码 + * @param size 每页数目 + * @return / + */ + public List findKeysForPage(String patternKey, int page, int size) { + ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); + RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); + RedisConnection rc = Objects.requireNonNull(factory).getConnection(); + Cursor cursor = rc.scan(options); + List result = new ArrayList<>(size); + int tmpIndex = 0; + int fromIndex = page * size; + int toIndex = page * size + size; + while (cursor.hasNext()) { + if (tmpIndex >= fromIndex && tmpIndex < toIndex) { + result.add(new String(cursor.next())); + tmpIndex++; + continue; + } + // 获取到满足条件的数据后,就可以退出了 + if(tmpIndex >=toIndex) { + break; + } + tmpIndex++; + cursor.next(); + } + try { + RedisConnectionUtils.releaseConnection(rc, factory); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 判断key是否存在 + * @param key 键 + * @return true 存在 false不存在 + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 删除缓存 + * @param key 可以传一个值 或多个 + */ + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete(CollectionUtils.arrayToList(key)); + } + } + } + + // ============================String============================= + + /** + * 普通缓存获取 + * @param key 键 + * @return 值 + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 批量获取 + * @param keys + * @return + */ + public List multiGet(List keys) { + Object obj = redisTemplate.opsForValue().multiGet(Collections.singleton(keys)); + return null; + } + + /** + * 普通缓存放入 + * @param key 键 + * @param value 值 + * @return true成功 false失败 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * @param key 键 + * @param value 值 + * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 + * @return true成功 false 失败 + */ + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * @param key 键 + * @param value 值 + * @param time 时间 + * @param timeUnit 类型 + * @return true成功 false 失败 + */ + public boolean set(String key, Object value, long time, TimeUnit timeUnit) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, timeUnit); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + // ================================Map================================= + + /** + * HashGet + * @param key 键 不能为null + * @param item 项 不能为null + * @return 值 + */ + public Object hget(String key, String item) { + return redisTemplate.opsForHash().get(key, item); + } + + /** + * 获取hashKey对应的所有键值 + * @param key 键 + * @return 对应的多个键值 + */ + public Map hmget(String key) { + return redisTemplate.opsForHash().entries(key); + + } + + /** + * HashSet + * @param key 键 + * @param map 对应多个键值 + * @return true 成功 false 失败 + */ + public boolean hmset(String key, Map map) { + try { + redisTemplate.opsForHash().putAll(key, map); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * HashSet 并设置时间 + * @param key 键 + * @param map 对应多个键值 + * @param time 时间(秒) + * @return true成功 false失败 + */ + public boolean hmset(String key, Map map, long time) { + try { + redisTemplate.opsForHash().putAll(key, map); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * + * @param key 键 + * @param item 项 + * @param value 值 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value) { + try { + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * + * @param key 键 + * @param item 项 + * @param value 值 + * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value, long time) { + try { + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 删除hash表中的值 + * + * @param key 键 不能为null + * @param item 项 可以使多个 不能为null + */ + public void hdel(String key, Object... item) { + redisTemplate.opsForHash().delete(key, item); + } + + /** + * 判断hash表中是否有该项的值 + * + * @param key 键 不能为null + * @param item 项 不能为null + * @return true 存在 false不存在 + */ + public boolean hHasKey(String key, String item) { + return redisTemplate.opsForHash().hasKey(key, item); + } + + /** + * hash递增 如果不存在,就会创建一个 并把新增后的值返回 + * + * @param key 键 + * @param item 项 + * @param by 要增加几(大于0) + * @return + */ + public double hincr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, by); + } + + /** + * hash递减 + * + * @param key 键 + * @param item 项 + * @param by 要减少记(小于0) + * @return + */ + public double hdecr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, -by); + } + + // ============================set============================= + + /** + * 根据key获取Set中的所有值 + * + * @param key 键 + * @return + */ + public Set sGet(String key) { + try { + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 根据value从一个set中查询,是否存在 + * + * @param key 键 + * @param value 值 + * @return true 存在 false不存在 + */ + public boolean sHasKey(String key, Object value) { + try { + return redisTemplate.opsForSet().isMember(key, value); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 将数据放入set缓存 + * + * @param key 键 + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSet(String key, Object... values) { + try { + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 将set数据放入缓存 + * @param key 键 + * @param time 时间(秒) + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSetAndTime(String key, long time, Object... values) { + try { + Long count = redisTemplate.opsForSet().add(key, values); + if (time > 0) { + expire(key, time); + } + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 获取set缓存的长度 + * @param key 键 + * @return + */ + public long sGetSetSize(String key) { + try { + return redisTemplate.opsForSet().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 移除值为value的 + * @param key 键 + * @param values 值 可以是多个 + * @return 移除的个数 + */ + public long setRemove(String key, Object... values) { + try { + Long count = redisTemplate.opsForSet().remove(key, values); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + // ===============================list================================= + + /** + * 获取list缓存的内容 + * @param key 键 + * @param start 开始 + * @param end 结束 0 到 -1代表所有值 + * @return + */ + public List lGet(String key, long start, long end) { + try { + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 获取list缓存的长度 + * @param key 键 + * @return + */ + public long lGetListSize(String key) { + try { + return redisTemplate.opsForList().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 通过索引 获取list中的值 + * @param key 键 + * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 + * @return + */ + public Object lGetIndex(String key, long index) { + try { + return redisTemplate.opsForList().index(key, index); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将list放入缓存 + * @param key 键 + * @param value 值 + * @return + */ + public boolean lSet(String key, Object value) { + try { + redisTemplate.opsForList().rightPush(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 将list放入缓存 + * @param key 键 + * @param value 值 + * @param time 时间(秒) + * @return + */ + public boolean lSet(String key, Object value, long time) { + try { + redisTemplate.opsForList().rightPush(key, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 将list放入缓存 + * @param key 键 + * @param value 值 + * @return + */ + public boolean lSet(String key, List value) { + try { + redisTemplate.opsForList().rightPushAll(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 将list放入缓存 + * @param key 键 + * @param value 值 + * @param time 时间(秒) + * @return + */ + public boolean lSet(String key, List value, long time) { + try { + redisTemplate.opsForList().rightPushAll(key, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 根据索引修改list中的某条数据 + * @param key 键 + * @param index 索引 + * @param value 值 + * @return / + */ + public boolean lUpdateIndex(String key, long index, Object value) { + try { + redisTemplate.opsForList().set(key, index, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 移除N个值为value + * @param key 键 + * @param count 移除多少个 + * @param value 值 + * @return 移除的个数 + */ + public long lRemove(String key, long count, Object value) { + try { + return redisTemplate.opsForList().remove(key, count, value); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } +} diff --git a/eladmin-system/src/main/java/me/zhengjie/modules/monitor/rest/RedisController.java b/eladmin-system/src/main/java/me/zhengjie/modules/monitor/rest/RedisController.java deleted file mode 100644 index 11967500..00000000 --- a/eladmin-system/src/main/java/me/zhengjie/modules/monitor/rest/RedisController.java +++ /dev/null @@ -1,65 +0,0 @@ -package me.zhengjie.modules.monitor.rest; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import me.zhengjie.aop.log.Log; -import me.zhengjie.modules.monitor.domain.vo.RedisVo; -import me.zhengjie.modules.monitor.service.RedisService; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author Zheng Jie - * @date 2018-12-10 - */ -@RestController -@RequestMapping("/api/redis") -@Api(tags = "系统:Redis缓存管理") -public class RedisController { - - private final RedisService redisService; - - public RedisController(RedisService redisService) { - this.redisService = redisService; - } - - @Log("查询Redis缓存") - @GetMapping - @ApiOperation("查询Redis缓存") - @PreAuthorize("@el.check('redis:list')") - public ResponseEntity getRedis(String key, Pageable pageable){ - return new ResponseEntity<>(redisService.findByKey(key,pageable), HttpStatus.OK); - } - - @Log("导出数据") - @ApiOperation("导出数据") - @GetMapping(value = "/download") - @PreAuthorize("@el.check('redis:list')") - public void download(HttpServletResponse response, String key) throws IOException { - redisService.download(redisService.findByKey(key), response); - } - - @Log("删除Redis缓存") - @DeleteMapping - @ApiOperation("删除Redis缓存") - @PreAuthorize("@el.check('redis:del')") - public ResponseEntity delete(@RequestBody RedisVo resources){ - redisService.delete(resources.getKey()); - return new ResponseEntity(HttpStatus.OK); - } - - @Log("清空Redis缓存") - @DeleteMapping(value = "/all") - @ApiOperation("清空Redis缓存") - @PreAuthorize("@el.check('redis:del')") - public ResponseEntity deleteAll(){ - redisService.deleteAll(); - return new ResponseEntity(HttpStatus.OK); - } -} diff --git a/eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/RedisService.java b/eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/RedisService.java deleted file mode 100644 index 3f5271a6..00000000 --- a/eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/RedisService.java +++ /dev/null @@ -1,65 +0,0 @@ -package me.zhengjie.modules.monitor.service; - -import me.zhengjie.modules.monitor.domain.vo.RedisVo; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.List; - -/** - * 可自行扩展 - * @author Zheng Jie - * @date 2018-12-10 - */ -public interface RedisService { - - /** - * 根据KEY查询 - * @param key 键 - * @param pageable 分页参数 - * @return / - */ - Page findByKey(String key, Pageable pageable); - - /** - * findById - * @param key 键 - * @return / - */ - List findByKey(String key); - - /** - * 查询验证码的值 - * @param key 键 - * @return / - */ - String getCodeVal(String key); - - /** - * 保存验证码 - * @param key 键 - * @param val 值 - */ - void saveCode(String key, Object val); - - /** - * delete - * @param key 键 - */ - void delete(String key); - - /** - * 清空缓存 - */ - void deleteAll(); - - /** - * 导出数据 - * @param redisVos / - * @param response / - * @throws IOException / - */ - void download(List redisVos, HttpServletResponse response) throws IOException; -} diff --git a/eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/impl/RedisServiceImpl.java b/eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/impl/RedisServiceImpl.java deleted file mode 100644 index 991ef865..00000000 --- a/eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/impl/RedisServiceImpl.java +++ /dev/null @@ -1,103 +0,0 @@ -package me.zhengjie.modules.monitor.service.impl; - -import me.zhengjie.modules.monitor.domain.vo.RedisVo; -import me.zhengjie.modules.monitor.service.RedisService; -import me.zhengjie.modules.security.config.SecurityProperties; -import me.zhengjie.utils.FileUtil; -import me.zhengjie.utils.PageUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -/** - * @author Zheng Jie - * @date 2018-12-10 - */ -@Service -@SuppressWarnings({"unchecked","all"}) -public class RedisServiceImpl implements RedisService { - - private final RedisTemplate redisTemplate; - private final SecurityProperties properties; - @Value("${loginCode.expiration}") - private Long expiration; - - public RedisServiceImpl(RedisTemplate redisTemplate, SecurityProperties properties) { - this.redisTemplate = redisTemplate; - this.properties = properties; - } - - @Override - public Page findByKey(String key, Pageable pageable){ - List redisVos = findByKey(key); - return new PageImpl( - PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),redisVos), - pageable, - redisVos.size()); - } - - @Override - public List findByKey(String key) { - List redisVos = new ArrayList<>(); - if(!"*".equals(key)){ - key = "*" + key + "*"; - } - Set keys = redisTemplate.keys(key); - for (String s : keys) { - // 过滤掉权限的缓存 - if (s.contains("role::loadPermissionByUser") || s.contains("user::loadUserByUsername") || s.contains(properties.getOnlineKey()) || s.contains(properties.getCodeKey())) { - continue; - } - RedisVo redisVo = new RedisVo(s, Objects.requireNonNull(redisTemplate.opsForValue().get(s)).toString()); - redisVos.add(redisVo); - } - return redisVos; - } - - @Override - public void delete(String key) { - redisTemplate.delete(key); - } - - @Override - public void deleteAll() { - Set keys = redisTemplate.keys( "*"); - redisTemplate.delete(keys.stream().filter(s -> !s.contains(properties.getOnlineKey())).filter(s -> !s.contains(properties.getCodeKey())).collect(Collectors.toList())); - } - - @Override - public String getCodeVal(String key) { - try { - return Objects.requireNonNull(redisTemplate.opsForValue().get(key)).toString(); - }catch (Exception e){ - return ""; - } - } - - @Override - public void saveCode(String key, Object val) { - redisTemplate.opsForValue().set(key,val); - redisTemplate.expire(key,expiration, TimeUnit.MINUTES); - } - - @Override - public void download(List redisVos, HttpServletResponse response) throws IOException { - List> list = new ArrayList<>(); - for (RedisVo redisVo : redisVos) { - Map map = new LinkedHashMap<>(); - map.put("key", redisVo.getKey()); - map.put("value", redisVo.getValue()); - list.add(map); - } - FileUtil.downloadExcel(list, response); - } -} diff --git a/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java b/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java index e052d916..edea9296 100644 --- a/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java +++ b/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java @@ -8,14 +8,15 @@ import lombok.extern.slf4j.Slf4j; import me.zhengjie.annotation.AnonymousAccess; import me.zhengjie.aop.log.Log; import me.zhengjie.exception.BadRequestException; -import me.zhengjie.modules.monitor.service.RedisService; import me.zhengjie.modules.security.config.SecurityProperties; import me.zhengjie.modules.security.security.TokenProvider; import me.zhengjie.modules.security.security.vo.AuthUser; import me.zhengjie.modules.security.security.vo.JwtUser; import me.zhengjie.modules.security.service.OnlineUserService; +import me.zhengjie.utils.RedisUtils; import me.zhengjie.utils.SecurityUtils; import me.zhengjie.utils.StringUtils; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -28,6 +29,7 @@ import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.TimeUnit; /** * @author Zheng Jie @@ -40,16 +42,18 @@ import java.util.Map; @Api(tags = "系统:系统授权接口") public class AuthController { + @Value("${loginCode.expiration}") + private Long expiration; private final SecurityProperties properties; - private final RedisService redisService; + private final RedisUtils redisUtils; private final UserDetailsService userDetailsService; private final OnlineUserService onlineUserService; private final TokenProvider tokenProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; - public AuthController(SecurityProperties properties, RedisService redisService, UserDetailsService userDetailsService, OnlineUserService onlineUserService, TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { + public AuthController(SecurityProperties properties, RedisUtils redisUtils, UserDetailsService userDetailsService, OnlineUserService onlineUserService, TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { this.properties = properties; - this.redisService = redisService; + this.redisUtils = redisUtils; this.userDetailsService = userDetailsService; this.onlineUserService = onlineUserService; this.tokenProvider = tokenProvider; @@ -62,11 +66,11 @@ public class AuthController { @PostMapping(value = "/login") public ResponseEntity login(@Validated @RequestBody AuthUser authUser, HttpServletRequest request){ // 查询验证码 - String code = redisService.getCodeVal(authUser.getUuid()); + String code = (String) redisUtils.get(authUser.getUuid()); // 清除验证码 - redisService.delete(authUser.getUuid()); + redisUtils.del(authUser.getUuid()); if (StringUtils.isBlank(code)) { - throw new BadRequestException("验证码已过期"); + throw new BadRequestException("验证码不存在或已过期"); } if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) { throw new BadRequestException("验证码错误"); @@ -108,7 +112,8 @@ public class AuthController { // 获取运算的结果 String result = captcha.text(); String uuid = properties.getCodeKey() + IdUtil.simpleUUID(); - redisService.saveCode(uuid,result); + // 保存 + redisUtils.set(uuid, result, expiration, TimeUnit.MINUTES); // 验证码信息 Map imgResult = new HashMap(2){{ put("img", captcha.toBase64()); diff --git a/eladmin-system/src/main/java/me/zhengjie/modules/security/service/OnlineUserService.java b/eladmin-system/src/main/java/me/zhengjie/modules/security/service/OnlineUserService.java index 0a1f4943..4c318410 100644 --- a/eladmin-system/src/main/java/me/zhengjie/modules/security/service/OnlineUserService.java +++ b/eladmin-system/src/main/java/me/zhengjie/modules/security/service/OnlineUserService.java @@ -3,42 +3,34 @@ package me.zhengjie.modules.security.service; import me.zhengjie.modules.security.config.SecurityProperties; import me.zhengjie.modules.security.security.vo.JwtUser; import me.zhengjie.modules.security.security.vo.OnlineUser; -import me.zhengjie.utils.EncryptUtils; -import me.zhengjie.utils.FileUtil; -import me.zhengjie.utils.PageUtil; -import me.zhengjie.utils.StringUtils; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; +import me.zhengjie.utils.*; import org.springframework.data.domain.Pageable; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; -import java.util.concurrent.TimeUnit; /** * @author Zheng Jie * @Date 2019年10月26日21:56:27 */ @Service -@SuppressWarnings({"unchecked","all"}) public class OnlineUserService { private final SecurityProperties properties; - private final RedisTemplate redisTemplate; + private RedisUtils redisUtils; - public OnlineUserService(SecurityProperties properties, RedisTemplate redisTemplate) { + public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) { this.properties = properties; - this.redisTemplate = redisTemplate; + this.redisUtils = redisUtils; } /** * 保存在线用户信息 - * @param jwtUser - * @param token - * @param request + * @param jwtUser / + * @param token / + * @param request / */ public void save(JwtUser jwtUser, String token, HttpServletRequest request){ String job = jwtUser.getDept() + "/" + jwtUser.getJob(); @@ -51,35 +43,34 @@ public class OnlineUserService { } catch (Exception e) { e.printStackTrace(); } - redisTemplate.opsForValue().set(properties.getOnlineKey() + token, onlineUser); - redisTemplate.expire(properties.getOnlineKey() + token,properties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS); + redisUtils.set(properties.getOnlineKey() + token, onlineUser, properties.getTokenValidityInSeconds()/1000); } /** * 查询全部数据 - * @param filter - * @param pageable - * @return + * @param filter / + * @param pageable / + * @return / */ - public Page getAll(String filter, Pageable pageable){ + public Map getAll(String filter, Pageable pageable){ List onlineUsers = getAll(filter); - return new PageImpl( + return PageUtil.toPage( PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),onlineUsers), - pageable, - onlineUsers.size()); + onlineUsers.size() + ); } /** * 查询全部数据,不分页 - * @param filter - * @return + * @param filter / + * @return / */ public List getAll(String filter){ - List keys = new ArrayList<>(redisTemplate.keys(properties.getOnlineKey() + "*")); + List keys = redisUtils.scan(properties.getOnlineKey() + "*"); Collections.reverse(keys); List onlineUsers = new ArrayList<>(); for (String key : keys) { - OnlineUser onlineUser = (OnlineUser) redisTemplate.opsForValue().get(key); + OnlineUser onlineUser = (OnlineUser) redisUtils.get(key); if(StringUtils.isNotBlank(filter)){ if(onlineUser.toString().contains(filter)){ onlineUsers.add(onlineUser); @@ -88,36 +79,34 @@ public class OnlineUserService { onlineUsers.add(onlineUser); } } - Collections.sort(onlineUsers, (o1, o2) -> { - return o2.getLoginTime().compareTo(o1.getLoginTime()); - }); + onlineUsers.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime())); return onlineUsers; } /** * 踢出用户 - * @param val - * @throws Exception + * @param key / + * @throws Exception / */ - public void kickOut(String val) throws Exception { - String key = properties.getOnlineKey() + EncryptUtils.desDecrypt(val); - redisTemplate.delete(key); + public void kickOut(String key) throws Exception { + key = properties.getOnlineKey() + EncryptUtils.desDecrypt(key); + redisUtils.del(key); } /** * 退出登录 - * @param token + * @param token / */ public void logout(String token) { String key = properties.getOnlineKey() + token; - redisTemplate.delete(key); + redisUtils.del(key); } /** * 导出 - * @param all - * @param response - * @throws IOException + * @param all / + * @param response / + * @throws IOException / */ public void download(List all, HttpServletResponse response) throws IOException { List> list = new ArrayList<>(); @@ -136,10 +125,10 @@ public class OnlineUserService { /** * 查询用户 - * @param key - * @return + * @param key / + * @return / */ public OnlineUser getOne(String key) { - return (OnlineUser)redisTemplate.opsForValue().get(key); + return (OnlineUser)redisUtils.get(key); } } diff --git a/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java b/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java index b71d638c..88b85a00 100644 --- a/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java +++ b/eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/UserServiceImpl.java @@ -1,6 +1,5 @@ package me.zhengjie.modules.system.service.impl; -import me.zhengjie.modules.monitor.service.RedisService; import me.zhengjie.modules.system.domain.User; import me.zhengjie.exception.EntityExistException; import me.zhengjie.exception.EntityNotFoundException; @@ -42,17 +41,17 @@ public class UserServiceImpl implements UserService { private final UserMapper userMapper; - private final RedisService redisService; + private final RedisUtils redisUtils; private final UserAvatarRepository userAvatarRepository; @Value("${file.avatar}") private String avatar; - public UserServiceImpl(UserRepository userRepository, UserMapper userMapper, RedisService redisService, UserAvatarRepository userAvatarRepository) { + public UserServiceImpl(UserRepository userRepository, UserMapper userMapper, RedisUtils redisUtils, UserAvatarRepository userAvatarRepository) { this.userRepository = userRepository; this.userMapper = userMapper; - this.redisService = redisService; + this.redisUtils = redisUtils; this.userAvatarRepository = userAvatarRepository; } @@ -116,9 +115,9 @@ public class UserServiceImpl implements UserService { // 如果用户的角色改变了,需要手动清理下缓存 if (!resources.getRoles().equals(user.getRoles())) { String key = "role::loadPermissionByUser:" + user.getUsername(); - redisService.delete(key); + redisUtils.del(key); key = "role::findByUsers_Id:" + user.getId(); - redisService.delete(key); + redisUtils.del(key); } user.setUsername(resources.getUsername());