Pārlūkot izejas kodu

加入spring cache

wangliang 5 gadi atpakaļ
vecāks
revīzija
59346434b4

+ 66 - 4
themis-backend/src/main/java/com/qmth/themis/backend/api/TBOrgController.java

@@ -1,8 +1,25 @@
 package com.qmth.themis.backend.api;
 
-import io.swagger.annotations.Api;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.qmth.themis.backend.util.ServletUtil;
+import com.qmth.themis.business.constant.SystemConstant;
+import com.qmth.themis.business.entity.TBOrg;
+import com.qmth.themis.business.entity.TBUser;
+import com.qmth.themis.business.service.TBOrgService;
+import com.qmth.themis.business.util.JacksonUtil;
+import com.qmth.themis.common.contanst.Constants;
+import com.qmth.themis.common.util.Result;
+import com.qmth.themis.common.util.ResultUtil;
+import io.swagger.annotations.*;
+import org.springframework.cache.CacheManager;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
 
 /**
  * @Description: 机构 前端控制器
@@ -16,4 +33,49 @@ import org.springframework.web.bind.annotation.RestController;
 @RequestMapping("/${prefix.url.admin}/org")
 public class TBOrgController {
 
-}
+    @Resource
+    TBOrgService tbOrgService;
+
+    @Resource
+    private CacheManager cacheManager;
+
+    //    @CachePut(value = "org_cache", key = "'orgCacheQuery'")
+    @ApiOperation(value = "机构查询接口")
+    @RequestMapping(value = "/query", method = RequestMethod.GET)
+    @ApiResponses({@ApiResponse(code = 200, message = "机构信息", response = TBOrg.class)})
+    public Result query(@ApiParam(value = "机构id", required = false) @RequestParam(required = false) Long id, @ApiParam(value = "机构编码", required = false) @RequestParam(required = false) String code, @ApiParam(value = "机构名称", required = false) @RequestParam(required = false) String name, @ApiParam(value = "是否启用", required = false) @RequestParam(required = false) Integer enable, HttpServletRequest request) {
+        QueryWrapper<TBOrg> tbOrgQueryWrapper = new QueryWrapper<>();
+        if (Objects.nonNull(id)) {
+            tbOrgQueryWrapper.lambda().eq(TBOrg::getId, id);
+        }
+        if (Objects.nonNull(code)) {
+            tbOrgQueryWrapper.lambda().eq(TBOrg::getCode, code);
+        }
+        if (Objects.nonNull(name)) {
+            tbOrgQueryWrapper.lambda().like(TBOrg::getName, name);
+        }
+        if (Objects.nonNull(enable)) {
+            tbOrgQueryWrapper.lambda().eq(TBOrg::getEnable, enable);
+        }
+        List<TBOrg> tbOrgList = tbOrgService.list(tbOrgQueryWrapper);
+        Map map = new HashMap<>();
+        map.put(SystemConstant.RECORDS, tbOrgList);
+        return ResultUtil.ok(map);
+    }
+
+    //    @CacheEvict(value = "org_cache", key = "'orgCacheQuery'")
+    @ApiOperation(value = "机构新增/编辑接口")
+    @RequestMapping(value = "/save", method = RequestMethod.POST)
+    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
+    public Result save(@ApiParam(value = "机构信息", required = true) @RequestBody TBOrg tbOrg, HttpServletRequest request) {
+        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount(request);
+        if (Objects.isNull(tbOrg.getId())) {
+            tbOrg.setId(Constants.idGen.next());
+            tbOrg.setCreateId(tbUser.getId());
+        } else {
+            tbOrg.setUpdateId(tbUser.getId());
+        }
+        tbOrgService.saveOrUpdate(tbOrg);
+        return ResultUtil.ok(JacksonUtil.parseJson(SystemConstant.SUCCESS));
+    }
+}

+ 70 - 18
themis-backend/src/main/java/com/qmth/themis/backend/api/TBUserController.java

@@ -1,16 +1,19 @@
 package com.qmth.themis.backend.api;
 
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.google.gson.Gson;
 import com.qmth.themis.backend.config.DictionaryConfig;
 import com.qmth.themis.backend.util.ServletUtil;
 import com.qmth.themis.business.constant.SystemConstant;
 import com.qmth.themis.business.dto.AuthDto;
 import com.qmth.themis.business.entity.TBSession;
 import com.qmth.themis.business.entity.TBUser;
+import com.qmth.themis.business.entity.TBUserRole;
 import com.qmth.themis.business.enums.MqEnum;
 import com.qmth.themis.business.enums.RoleEnum;
 import com.qmth.themis.business.enums.SystemOperationEnum;
 import com.qmth.themis.business.service.EhcacheService;
+import com.qmth.themis.business.service.TBUserRoleService;
 import com.qmth.themis.business.service.TBUserService;
 import com.qmth.themis.business.util.EhcacheUtil;
 import com.qmth.themis.business.util.JacksonUtil;
@@ -31,20 +34,13 @@ import io.swagger.annotations.*;
 import org.apache.commons.lang3.RandomStringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
-import java.io.UnsupportedEncodingException;
 import java.security.NoSuchAlgorithmException;
-import java.security.spec.InvalidKeySpecException;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
+import java.util.*;
 
 /**
  * @Description: 用户 前端控制器
@@ -74,10 +70,13 @@ public class TBUserController {
     @Resource
     MqDtoService mqDtoService;
 
+    @Resource
+    TBUserRoleService tbUserRoleService;
+
     @ApiOperation(value = "用户登录接口")
     @RequestMapping(value = "/login/account", method = RequestMethod.POST)
     @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = TBUser.class)})
-    public Result login(@ApiParam(value = "用户信息", required = true) @RequestBody TBUser tbUser, HttpServletRequest request) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
+    public Result login(@ApiParam(value = "用户信息", required = true) @RequestBody TBUser tbUser, HttpServletRequest request) throws NoSuchAlgorithmException {
         if (Objects.isNull(tbUser.getLoginName()) || Objects.equals(tbUser.getLoginName(), "")) {
             throw new BusinessException(ExceptionResultEnum.LOGIN_NAME_IS_NULL);
         }
@@ -113,7 +112,7 @@ public class TBUserController {
         //添加用户缓存
         redisUtil.setUser(user.getId(), user);
         //添加用户会话缓存
-        String sessionId = SessionUtil.digest(user.getId(), authDto.getRoleCodes().toString(), platform.getSource());
+        String sessionId = SessionUtil.digest(user.getId(), authDto.getRoleCodes().toString().replaceAll(",", "&&").replaceAll(" ", ""), platform.getSource());
 
         Date expire = SystemConstant.getExpireTime(platform);
         TBSession tbSession = new TBSession(sessionId, String.valueOf(user.getId()), authDto.getRoleCodes().toString(), platform.getSource(), platform.name(), deviceId, request.getLocalAddr(), token, expire);
@@ -129,11 +128,13 @@ public class TBUserController {
         map.put(SystemConstant.ACCESS_TOKEN, test);
         map.put(SystemConstant.ACCOUNT, user);
         map.put(SystemConstant.SESSION_ID, sessionId);
-        Map orgMap = new HashMap();
-        orgMap.put("name", authDto.getTbOrg().getName());
-        orgMap.put("logo", authDto.getTbOrg().getLogo());
-        orgMap.put("enableVideoRecord", authDto.getTbOrg().getEnableVideoRecord());
-        map.put(SystemConstant.ORG_INFO, orgMap);
+        if (Objects.nonNull(authDto.getTbOrg())) {
+            Map orgMap = new HashMap();
+            orgMap.put("name", authDto.getTbOrg().getName());
+            orgMap.put("logo", authDto.getTbOrg().getLogo());
+            orgMap.put("enableVideoRecord", authDto.getTbOrg().getEnableVideoRecord());
+            map.put(SystemConstant.ORG_INFO, orgMap);
+        }
         return ResultUtil.ok(map);
     }
 
@@ -452,7 +453,7 @@ public class TBUserController {
         //循环检查该用户下其他平台是否存在session,不存在则删除用户缓存和鉴权缓存
         boolean delete = true;
         for (Source s : Source.values()) {
-            String sessionId = SessionUtil.digest(tbUser.getId(), authDto.getRoleCodes().toString(), s.name());
+            String sessionId = SessionUtil.digest(tbUser.getId(), authDto.getRoleCodes().toString().replaceAll(",", "&&").replaceAll(" ", ""), s.name());
             if (Objects.nonNull(redisUtil.getUserSession(sessionId))) {
                 delete = false;
                 break;
@@ -467,4 +468,55 @@ public class TBUserController {
         //mq发送消息end
         return ResultUtil.ok(JacksonUtil.parseJson(SystemConstant.SUCCESS));
     }
+
+    //    @CachePut(value = "user_cache", key = "'userCacheQuery'")
+    @ApiOperation(value = "用户查询接口")
+    @RequestMapping(value = "/query", method = RequestMethod.GET)
+    @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = TBUser.class)})
+    public Result query(@ApiParam(value = "用户id", required = false) @RequestParam(required = false) Long id, @ApiParam(value = "登录名", required = false) @RequestParam(required = false) String loginName, @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String name, @ApiParam(value = "角色", required = false) @RequestParam(required = false) String role, @ApiParam(value = "是否启用", required = false) @RequestParam(required = false) Integer enable, HttpServletRequest request) {
+        List<TBUser> tbUserList = tbUserService.userQuery(id, loginName, name, role, enable);
+        Map map = new HashMap<>();
+        map.put(SystemConstant.RECORDS, tbUserList);
+        return ResultUtil.ok(map);
+    }
+
+    //    @CacheEvict(value = "user_cache", key = "'userCacheQuery'")
+    @ApiOperation(value = "用户新增/编辑接口")
+    @RequestMapping(value = "/save", method = RequestMethod.POST)
+    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
+    @Transactional
+    public Result save(@ApiParam(value = "机构信息", required = true) @RequestBody Map<String, Object> mapParameter, HttpServletRequest request) {
+        Gson gson = new Gson();
+        TBUser tbUser = gson.fromJson(gson.toJson(mapParameter), TBUser.class);
+        List<String> roleList = (List<String>) mapParameter.get("role");
+        Set<String> roleSet = null;
+        if (Objects.nonNull(roleList) && roleList.size() > 0) {
+            roleSet = new HashSet<>(roleList);
+        }
+        //todo orgId待从redis取
+        if (Objects.isNull(tbUser.getId())) {
+            tbUser.setId(Constants.idGen.next());
+            tbUser.setCreateId(tbUser.getId());
+            if (Objects.nonNull(roleSet) && roleSet.size() > 0) {
+                roleSet.forEach(s -> {
+                    TBUserRole tbUserRole = new TBUserRole(tbUser.getId(), s);
+                    tbUserRoleService.save(tbUserRole);
+                });
+            }
+        } else {
+            if (Objects.nonNull(roleSet) && roleSet.size() > 0) {
+                QueryWrapper<TBUserRole> tbUserRoleQueryWrapper = new QueryWrapper<>();
+                tbUserRoleQueryWrapper.lambda().eq(TBUserRole::getUserId, tbUser.getId());
+                tbUserRoleService.remove(tbUserRoleQueryWrapper);
+                roleSet.forEach(s -> {
+                    TBUserRole tbUserRole = new TBUserRole(tbUser.getId(), s);
+                    tbUserRoleService.save(tbUserRole);
+                });
+                ehcacheService.removeAccountCache(tbUser.getId());
+            }
+            tbUser.setUpdateId(tbUser.getId());
+        }
+        tbUserService.saveOrUpdate(tbUser);
+        return ResultUtil.ok(JacksonUtil.parseJson(SystemConstant.SUCCESS));
+    }
 }

+ 11 - 7
themis-backend/src/main/java/com/qmth/themis/backend/interceptor/AuthInterceptor.java

@@ -7,11 +7,11 @@ import com.qmth.themis.business.constant.SystemConstant;
 import com.qmth.themis.business.dto.AuthDto;
 import com.qmth.themis.business.entity.TBSession;
 import com.qmth.themis.business.entity.TBUser;
+import com.qmth.themis.business.enums.RoleEnum;
 import com.qmth.themis.business.service.EhcacheService;
 import com.qmth.themis.business.service.TBUserService;
 import com.qmth.themis.business.util.EhcacheUtil;
 import com.qmth.themis.business.util.RedisUtil;
-import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.enums.ExceptionResultEnum;
 import com.qmth.themis.common.enums.Platform;
 import com.qmth.themis.common.exception.BusinessException;
@@ -105,6 +105,16 @@ public class AuthInterceptor implements HandlerInterceptor {
 
                     request.setAttribute(SystemConstant.SESSION, tbSession);
                     request.setAttribute(SystemConstant.ACCOUNT, tbUser);
+
+                    AuthDto authDto = (AuthDto) EhcacheUtil.get(SystemConstant.AUTH_CACHE, userId);
+                    //验证权限
+                    if (Objects.isNull(authDto)) {
+                        authDto = ehcacheService.addAccountCache(userId);
+                    }
+                    //系统管理员拥有所有权限
+                    if (authDto.getRoleCodes().contains(RoleEnum.SUPER_ADMIN.name())) {
+                        return true;
+                    }
                     //系统公用接口不拦截
                     List<String> sysUrls = dictionaryConfig.systemUrlDomain().getUrls();
                     int sysCount = (int) sysUrls.stream().filter(s -> {
@@ -113,12 +123,6 @@ public class AuthInterceptor implements HandlerInterceptor {
                     if (sysCount > 0) {
                         return true;
                     }
-
-                    //验证权限
-                    AuthDto authDto = (AuthDto) EhcacheUtil.get(SystemConstant.AUTH_CACHE, userId);
-                    if (Objects.isNull(authDto)) {
-                        authDto = ehcacheService.addAccountCache(userId);
-                    }
                     Set<String> urls = authDto.getUrls();
                     int count = (int) urls.stream().filter(s -> {
                         return s.equalsIgnoreCase(url);

+ 20 - 0
themis-backend/src/main/resources/ehcache.xml

@@ -24,4 +24,24 @@
             timeToIdleSeconds="0"
             timeToLiveSeconds="43200"
             memoryStoreEvictionPolicy="LRU" />
+
+    <cache
+            name="org_cache"
+            eternal="false"
+            maxElementsInMemory="1000"
+            overflowToDisk="false"
+            diskPersistent="false"
+            timeToIdleSeconds="0"
+            timeToLiveSeconds="43200"
+            memoryStoreEvictionPolicy="LRU" />
+
+    <cache
+            name="user_cache"
+            eternal="false"
+            maxElementsInMemory="1000"
+            overflowToDisk="false"
+            diskPersistent="false"
+            timeToIdleSeconds="0"
+            timeToLiveSeconds="43200"
+            memoryStoreEvictionPolicy="LRU" />
 </ehcache>

+ 15 - 0
themis-business/src/main/java/com/qmth/themis/business/dao/TBUserMapper.java

@@ -3,6 +3,10 @@ package com.qmth.themis.business.dao;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.qmth.themis.business.entity.TBUser;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+import java.util.Map;
 
 /**
  * @Description: 用户 Mapper 接口
@@ -14,4 +18,15 @@ import org.apache.ibatis.annotations.Mapper;
 @Mapper
 public interface TBUserMapper extends BaseMapper<TBUser> {
 
+    /**
+     * 用户查询
+     *
+     * @param id
+     * @param loginName
+     * @param name
+     * @param role
+     * @param enable
+     * @return
+     */
+    List<TBUser> userQuery(@Param("id") Long id, @Param("loginName") String loginName, @Param("name") String name, @Param("role") String role, @Param("enable") Integer enable);
 }

+ 11 - 0
themis-business/src/main/java/com/qmth/themis/business/entity/TBUserRole.java

@@ -2,6 +2,7 @@ package com.qmth.themis.business.entity;
 
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
+import com.qmth.themis.common.contanst.Constants;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 
@@ -31,6 +32,16 @@ public class TBUserRole implements Serializable {
     @TableField(value = "role_code")
     private String roleCode;
 
+    public TBUserRole() {
+
+    }
+
+    public TBUserRole(Long userId, String roleCode) {
+        this.id = Constants.idGen.next();
+        this.userId = userId;
+        this.roleCode = roleCode;
+    }
+
     public static long getSerialVersionUID() {
         return serialVersionUID;
     }

+ 12 - 1
themis-business/src/main/java/com/qmth/themis/business/service/TBUserService.java

@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
 import com.qmth.themis.business.entity.TBUser;
 
 import java.util.List;
+import java.util.Map;
 
 /**
  * @Description: 用户 服务类
@@ -14,5 +15,15 @@ import java.util.List;
  */
 public interface TBUserService extends IService<TBUser> {
 
-    public List<TBUser> selectAllUser();
+    /**
+     * 用户查询
+     *
+     * @param id
+     * @param loginName
+     * @param name
+     * @param role
+     * @param enable
+     * @return
+     */
+    List<TBUser> userQuery(Long id, String loginName, String name, String role, Integer enable);
 }

+ 16 - 2
themis-business/src/main/java/com/qmth/themis/business/service/impl/TBUserServiceImpl.java

@@ -8,6 +8,7 @@ import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
 import java.util.List;
+import java.util.Map;
 
 /**
  * @Description: 用户 服务实现类
@@ -19,8 +20,21 @@ import java.util.List;
 @Service
 public class TBUserServiceImpl extends ServiceImpl<TBUserMapper, TBUser> implements TBUserService {
 
+    @Resource
+    TBUserMapper tbUserMapper;
+
+    /**
+     * 用户查询
+     *
+     * @param id
+     * @param loginName
+     * @param name
+     * @param role
+     * @param enable
+     * @return
+     */
     @Override
-    public List<TBUser> selectAllUser() {
-        return this.list();
+    public List<TBUser> userQuery(Long id, String loginName, String name, String role, Integer enable) {
+        return tbUserMapper.userQuery(id, loginName, name, role, enable);
     }
 }

+ 22 - 0
themis-business/src/main/resources/mapper/TBUserMapper.xml

@@ -2,4 +2,26 @@
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.qmth.themis.business.dao.TBUserMapper">
 
+    <select id="userQuery" resultType="com.qmth.themis.business.entity.TBUser">
+        select * from t_b_user tbu
+        left join t_b_user_role tbur on tbur.user_id = tbu.id
+        left join t_b_role tbr on tbr.role_code = tbur.role_code
+        <where>
+            <if test="id != null and id != ''">
+                and tbu.id = #{id}
+            </if>
+            <if test="loginName != null and loginName != ''">
+                and tbu.login_name like concat('%', #{loginName}, '%')
+            </if>
+            <if test="name != null and name != ''">
+                and tbu.name like concat('%', #{name}, '%')
+            </if>
+            <if test="enable != null and enable != ''">
+                and tbu.enable = #{enable}
+            </if>
+            <if test="role != null and role != ''">
+                and tbr.role_code = #{role}
+            </if>
+        </where>
+    </select>
 </mapper>

+ 0 - 2
themis-exam/src/main/java/com/qmth/themis/exam/api/TEExamStudentLogController.java

@@ -44,9 +44,7 @@ public class TEExamStudentLogController {
 //            @ApiParam(value = "日志信息", required = true) @RequestBody TEExamStudentLog tEExamStudentLog
     ) {
         log.info("saveLog is come in");
-        List<TBUser> tbUserList = tbUserService.selectAllUser();
         Map<String, Object> map = new HashMap<>();
-        map.put(SystemConstant.RECORDS, tbUserList);
 //        return ResultUtil.ok(SystemConstant.SUCCESS);
         return ResultUtil.ok(map);
     }