Browse Source

增加待考列表接口

wangliang 4 years ago
parent
commit
d6aad98c2d

+ 2 - 2
themis-business/src/main/java/com/qmth/themis/business/service/EhcacheService.java

@@ -29,10 +29,10 @@ public interface EhcacheService {
     /**
      * 添加学生缓存
      *
-     * @param o
+     * @param studentId
      * @return
      */
-    public AuthDto addStudentCache(Object o);
+    public AuthDto addStudentCache(Long studentId);
 
     /**
      * 删除学生缓存

+ 11 - 12
themis-business/src/main/java/com/qmth/themis/business/service/impl/EhcacheServiceImpl.java

@@ -11,6 +11,8 @@ import com.qmth.themis.common.enums.ExceptionResultEnum;
 import com.qmth.themis.common.exception.BusinessException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
@@ -81,7 +83,7 @@ public class EhcacheServiceImpl implements EhcacheService {
                     pWrapper.lambda().eq(TBPrivilege::getType, SystemConstant.LINK);
                     List<TBPrivilege> tbPrivilegeList = tbPrivilegeService.list(pWrapper);
                     authDto = new AuthDto(tbUserRoleList.stream().map(s -> s.getRoleCode()).collect(Collectors.toSet()), tbPrivilegeList.stream().map(s -> s.getUrl()).collect(Collectors.toSet()));
-                    EhcacheUtil.put(SystemConstant.AUTH_CACHE, user.getId(), authDto);
+//                    EhcacheUtil.put(SystemConstant.AUTH_CACHE, user.getId(), authDto);
                 } else {
                     TBOrg tbOrg = tbOrgService.getById(user.getOrgId());
                     //根据角色名查权限
@@ -94,7 +96,7 @@ public class EhcacheServiceImpl implements EhcacheService {
                     pWrapper.lambda().in(TBPrivilege::getId, privilegeIds).eq(TBPrivilege::getType, SystemConstant.LINK);
                     List<TBPrivilege> tbPrivilegeList = tbPrivilegeService.list(pWrapper);
                     authDto = new AuthDto(roleCodes, tbPrivilegeList.stream().map(s -> s.getUrl()).collect(Collectors.toSet()), tbOrg);
-                    EhcacheUtil.put(SystemConstant.AUTH_CACHE, user.getId(), authDto);
+//                    EhcacheUtil.put(SystemConstant.AUTH_CACHE, user.getId(), authDto);
                 }
             }
         } catch (Exception e) {
@@ -117,19 +119,15 @@ public class EhcacheServiceImpl implements EhcacheService {
     /**
      * 添加学生缓存
      *
-     * @param o
+     * @param studentId
      * @return
      */
     @Override
-    public AuthDto addStudentCache(Object o) {
+    @Cacheable(value = "student:oauth:cache", key = "#p0")
+    public AuthDto addStudentCache(Long studentId) {
         AuthDto authDto = null;
         try {
-            TEStudent teStudent = null;
-            if (o instanceof TEStudent) {
-                teStudent = (TEStudent) o;
-            } else {
-                teStudent = teStudentService.getById(Long.parseLong(String.valueOf(o)));
-            }
+            TEStudent teStudent = teStudentService.getById(studentId);
             if (Objects.isNull(teStudent)) {
                 throw new BusinessException(ExceptionResultEnum.STUDENT_NO);
             }
@@ -145,7 +143,7 @@ public class EhcacheServiceImpl implements EhcacheService {
             Set<String> roleCodes = new HashSet<>();
             roleCodes.add(RoleEnum.STUDENT.name());
             authDto = new AuthDto(roleCodes, tbPrivilegeList.stream().map(s -> s.getUrl()).collect(Collectors.toSet()), tbOrg);
-            EhcacheUtil.put(SystemConstant.STUDENT_CACHE, teStudent.getId(), authDto);
+//            EhcacheUtil.put(SystemConstant.STUDENT_CACHE, teStudent.getId(), authDto);
         } catch (Exception e) {
             e.printStackTrace();
             throw new BusinessException("添加学生缓存失败");
@@ -159,7 +157,8 @@ public class EhcacheServiceImpl implements EhcacheService {
      * @param studentId
      */
     @Override
+    @CacheEvict(value = "student:oauth:cache", key = "#p0")
     public void removeStudentCache(Long studentId) {
-        EhcacheUtil.remove(SystemConstant.STUDENT_CACHE, studentId);
+
     }
 }

+ 1 - 1
themis-business/src/main/java/com/qmth/themis/business/service/impl/TEConfigServiceImpl.java

@@ -26,7 +26,7 @@ public class TEConfigServiceImpl extends ServiceImpl<TEConfigMapper, TEConfig> i
      * @return
      */
     @Override
-    @Cacheable(value = "config_cache", key = "methodName")
+    @Cacheable(value = "config:cache", key = "methodName")
     public TEConfig getGlobalConfig() {
         List<TEConfig> teConfigList = this.list();
         return Objects.isNull(teConfigList) || teConfigList.size() == 0 ? null : teConfigList.get(0);

+ 41 - 3
themis-exam/src/main/java/com/qmth/themis/exam/ThemisExamApplication.java

@@ -6,24 +6,29 @@ import com.fasterxml.jackson.databind.ObjectMapper;
 import com.qmth.themis.common.contanst.Constants;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.domain.EntityScan;
-import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration;
 import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Primary;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.cache.RedisCacheManager;
+import org.springframework.data.redis.cache.RedisCacheWriter;
 import org.springframework.data.redis.connection.RedisConnectionFactory;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializationContext;
 import org.springframework.data.redis.serializer.StringRedisSerializer;
 import org.springframework.scheduling.annotation.EnableAsync;
-import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.transaction.annotation.EnableTransactionManagement;
 import org.springframework.web.multipart.MultipartResolver;
 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+
 @SpringBootApplication
 @ComponentScan(basePackages = {"com.qmth.themis"})
 @MapperScan("com.qmth.themis.business.dao")
@@ -53,6 +58,39 @@ public class ThemisExamApplication {
         return resolver;
     }
 
+    @Bean
+    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
+        return new RedisCacheManager(
+                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
+                this.getRedisCacheConfigurationWithTtl(40 * 60), // 默认策略,未配置的 key 会使用这个
+                this.getRedisCacheConfigurationMap() // 指定 key 策略
+        );
+    }
+
+    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
+        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
+        redisCacheConfigurationMap.put("student:oauth:cache", this.getRedisCacheConfigurationWithTtl(2 * 60 * 60));//一个小时
+        redisCacheConfigurationMap.put("config:cache", this.getRedisCacheConfigurationWithTtl(24 * 60 * 60));
+        return redisCacheConfigurationMap;
+    }
+
+    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
+        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
+        ObjectMapper om = new ObjectMapper();
+        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(om);
+
+        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
+        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
+                RedisSerializationContext
+                        .SerializationPair
+                        .fromSerializer(jackson2JsonRedisSerializer)
+        ).entryTtl(Duration.ofSeconds(seconds));
+        return redisCacheConfiguration;
+    }
+
+
     @Bean
     @Primary
     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

+ 9 - 3
themis-exam/src/main/java/com/qmth/themis/exam/api/TEStudentController.java

@@ -1,6 +1,7 @@
 package com.qmth.themis.exam.api;
 
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.qmth.themis.business.constant.SpringContextHolder;
 import com.qmth.themis.business.constant.SystemConstant;
 import com.qmth.themis.business.dto.AuthDto;
 import com.qmth.themis.business.entity.TBSession;
@@ -29,6 +30,7 @@ import com.qmth.themis.exam.util.ServletUtil;
 import com.qmth.themis.mq.service.MqDtoService;
 import io.swagger.annotations.*;
 import org.apache.commons.lang3.RandomStringUtils;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -74,6 +76,9 @@ public class TEStudentController {
     @Resource
     TOeExamRecordService tOeExamRecordService;
 
+    @Resource
+    RedisTemplate redisTemplate;
+
     @ApiOperation(value = "学生登录接口")
     @RequestMapping(value = "/login", method = RequestMethod.POST)
     @ApiResponses({@ApiResponse(code = 200, message = "学生信息", response = TEStudent.class)})
@@ -121,7 +126,7 @@ public class TEStudentController {
         Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
         String deviceId = ServletUtil.getRequestDeviceId();
         //添加用户鉴权缓存
-        AuthDto authDto = ehcacheService.addStudentCache(teStudent);
+        AuthDto authDto = ehcacheService.addStudentCache(teStudent.getId());
         //生成token
         String token = RandomStringUtils.randomAlphanumeric(32);
         //添加用户缓存
@@ -145,7 +150,7 @@ public class TEStudentController {
             List<Map> list = teExamService.getWaitingExam(teStudent.getId());
             map.put("waiting", list);
         } else {
-            unFinishExam.put("activity",unFinishExam);
+            unFinishExam.put("activity", unFinishExam);
             map.put("unFinished", unFinishExam);
         }
         //获取全局考试配置
@@ -164,10 +169,11 @@ public class TEStudentController {
     public Result logout() throws NoSuchAlgorithmException {
         TEStudent teStudent = (TEStudent) ServletUtil.getRequestStudentAccount();
         TBSession tbSession = (TBSession) ServletUtil.getRequestSession();
-        AuthDto authDto = (AuthDto) EhcacheUtil.get(SystemConstant.STUDENT_CACHE, teStudent.getId());
         if (Objects.isNull(tbSession)) {
             throw new BusinessException(ExceptionResultEnum.LOGIN_NO);
         }
+        AuthDto authDto = (AuthDto) redisTemplate.opsForValue().get("student:oauth:cache::" + teStudent.getId());
+//        AuthDto authDto = (AuthDto) EhcacheUtil.get(SystemConstant.STUDENT_CACHE, teStudent.getId());
         redisUtil.deleteUserSession(tbSession.getId());
         //循环检查该用户下其他平台是否存在session,不存在则删除用户缓存和鉴权缓存
         boolean delete = true;

+ 6 - 3
themis-exam/src/main/java/com/qmth/themis/exam/interceptor/AuthInterceptor.java

@@ -4,11 +4,9 @@ import cn.hutool.http.HttpStatus;
 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.TEStudent;
 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.service.TEStudentService;
 import com.qmth.themis.business.util.EhcacheUtil;
 import com.qmth.themis.business.util.RedisUtil;
@@ -21,6 +19,7 @@ import com.qmth.themis.exam.config.DictionaryConfig;
 import com.qmth.themis.exam.util.ServletUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.ModelAndView;
 
@@ -54,6 +53,9 @@ public class AuthInterceptor implements HandlerInterceptor {
     @Resource
     RedisUtil redisUtil;
 
+    @Resource
+    RedisTemplate redisTemplate;
+
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
         log.info("exam HandlerInterceptor preHandle is come in");
@@ -107,7 +109,8 @@ public class AuthInterceptor implements HandlerInterceptor {
                     request.setAttribute(SystemConstant.SESSION, tbSession);
                     request.setAttribute(SystemConstant.STUDENT_ACCOUNT, teStudent);
 
-                    AuthDto authDto = (AuthDto) EhcacheUtil.get(SystemConstant.STUDENT_CACHE, userId);
+//                    AuthDto authDto = (AuthDto) EhcacheUtil.get(SystemConstant.STUDENT_CACHE, userId);
+                    AuthDto authDto = (AuthDto) redisTemplate.opsForValue().get("student:oauth:cache::" + userId);
                     //验证权限
                     if (Objects.isNull(authDto)) {
                         authDto = ehcacheService.addStudentCache(userId);

+ 1 - 1
themis-exam/src/main/resources/application.properties

@@ -192,5 +192,5 @@ spring.resources.static-locations=file:${sys.config.serverUpload},classpath:/MET
 prefix.url.exam=api/oe
 
 #\u65E0\u9700\u9274\u6743\u7684url
-no.auth.urls=/webjars/**,/druid/**,/swagger-ui.html,/doc.html,/swagger-resources/**,/v2/api-docs,/webjars/springfox-swagger-ui/**,/api/oe/student/login,/file/**,/upload/**,/client/**,/base_photo/**,/api/oe/**
+no.auth.urls=/webjars/**,/druid/**,/swagger-ui.html,/doc.html,/swagger-resources/**,/v2/api-docs,/webjars/springfox-swagger-ui/**,/api/oe/student/login,/file/**,/upload/**,/client/**,/base_photo/**
 common.system.urls=/api/oe/student/logout

+ 9 - 9
themis-exam/src/main/resources/ehcache.xml

@@ -25,13 +25,13 @@
             timeToLiveSeconds="43200"
             memoryStoreEvictionPolicy="LRU" />
 
-    <cache
-            name="config_cache"
-            eternal="false"
-            maxElementsInMemory="1000"
-            overflowToDisk="false"
-            diskPersistent="false"
-            timeToIdleSeconds="0"
-            timeToLiveSeconds="43200"
-            memoryStoreEvictionPolicy="LRU" />
+<!--    <cache-->
+<!--            name="config_cache"-->
+<!--            eternal="false"-->
+<!--            maxElementsInMemory="1000"-->
+<!--            overflowToDisk="false"-->
+<!--            diskPersistent="false"-->
+<!--            timeToIdleSeconds="0"-->
+<!--            timeToLiveSeconds="43200"-->
+<!--            memoryStoreEvictionPolicy="LRU" />-->
 </ehcache>