Parcourir la source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

yeshijie il y a 6 ans
Parent
commit
2e4e65f454
19 fichiers modifiés avec 833 ajouts et 30 suppressions
  1. 36 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/RedisContext.java
  2. 34 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/WebMvcConfigurer.java
  3. 1 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/constant/LoginInfo.java
  4. 3 4
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/dfs/FastDFSController.java
  5. 27 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/facilities/FacilitiesController.java
  6. 12 5
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/FacilityUsedRecordController.java
  7. 14 13
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/UserController.java
  8. 12 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/user/UserDao.java
  9. 157 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/interceptor/ActivatedInterceptor.java
  10. 49 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/job/ActivatedUserUpdateTask.java
  11. 1 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/listener/RedisKeyExpirationListener.java
  12. 16 1
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/FacilityUsedRecord.java
  13. 13 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/User.java
  14. 71 2
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/facility/FacilityService.java
  15. 18 5
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/UserService.java
  16. 71 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/ImportDemoReader.java
  17. 167 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/RedisClient.java
  18. 127 0
      svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/RestTemplateUtil.java
  19. 4 0
      svr/svr-healthy-house/src/main/resources/application.yml

+ 36 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/RedisContext.java

@ -0,0 +1,36 @@
package com.yihu.jw.healthyhouse.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.11.25 17:33
 */
@Configuration
public class RedisContext {
    @Bean
    RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Serializable.class));
        redisTemplate.setHashValueSerializer(new GenericToStringSerializer<>(Long.class));
        return redisTemplate;
    }
//    @Bean
//    public static ConfigureRedisAction configureRedisAction() {
//        return ConfigureRedisAction.NO_OP;
//    }
}

+ 34 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/config/WebMvcConfigurer.java

@ -0,0 +1,34 @@
package com.yihu.jw.healthyhouse.config;
import com.yihu.jw.healthyhouse.interceptor.ActivatedInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
 * @author HZY
 * @created 2018/10/9 9:24
 */
//@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
//        registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
//        super.addInterceptors(registry);
//    }
    @Bean
    public ActivatedInterceptor authenticationInterceptor() {
        return new ActivatedInterceptor();
    }
}

+ 1 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/constant/LoginInfo.java

@ -5,6 +5,7 @@ package com.yihu.jw.healthyhouse.constant;
 * @created 2018/9/19 9:10
 */
public class LoginInfo {
    public static final String USER_INFO = "userInfo";
    public static final String IS_LOGIN = "isLogin";
    public static final String LOGIN_NAME = "loginName";
    public static final String LOGIN_CODE = "loginCode";

+ 3 - 4
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/dfs/FastDFSController.java

@ -75,7 +75,7 @@ public class FastDFSController extends EnvelopRestEndpoint {
        fileResource.setCreateUser(creator);
        fileResource=  fileResourceService.save(fileResource);
        path = groupName.substring(1, groupName.length() - 1) + "/" + remoteFileName.substring(1, remoteFileName.length() - 1);
        fileResource.setStoragePath( fastdfs_file_url + path);
        fileResource.setStoragePath(path);
        return success(fileResource);
    }
@ -107,14 +107,13 @@ public class FastDFSController extends EnvelopRestEndpoint {
        String path = groupName.substring(1, groupName.length() - 1) + ":" + remoteFileName.substring(1, remoteFileName.length() - 1);
        //路径存储到mysql数据库
        FileResource fileResource =new FileResource();
        //TODO
        fileResource.setObjectId("111");
        fileResource.setObjectId(paramMap.get("object"));
        fileResource.setStoragePath(path);
        fileResource.setFileSize(String.valueOf(fileSize));
        fileResource.setFileName(fileName);
        fileResource=  fileResourceService.save(fileResource);
         path = groupName.substring(1, groupName.length() - 1) + "/" + remoteFileName.substring(1, remoteFileName.length() - 1);
        fileResource.setStoragePath( fastdfs_file_url + path);
        fileResource.setStoragePath( path);
        return success(fileResource);
    }

+ 27 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/facilities/FacilitiesController.java

@ -7,6 +7,7 @@ import com.yihu.jw.healthyhouse.model.facility.FacilityServerRelation;
import com.yihu.jw.healthyhouse.service.facility.FacilityServerRelationService;
import com.yihu.jw.healthyhouse.service.facility.FacilityServerService;
import com.yihu.jw.healthyhouse.service.facility.FacilityService;
import com.yihu.jw.healthyhouse.util.ImportDemoReader;
import com.yihu.jw.healthyhouse.util.facility.FacilityMsgReader;
import com.yihu.jw.healthyhouse.util.facility.msg.FacilityMsg;
import com.yihu.jw.healthyhouse.util.poi.AExcelReader;
@ -234,6 +235,8 @@ public class FacilitiesController extends EnvelopRestEndpoint {
            return failed("设施不存在!");
        }
        facility.setDeleteFlag("1");
        //将设施状态改成关闭,在用户历史行程中做提示使用
        facility.setStatus("1");
        facilityService.save(facility);
        return success("success");
    }
@ -458,4 +461,28 @@ public class FacilitiesController extends EnvelopRestEndpoint {
    }
    @PostMapping(value = "/demoImport")
    @ApiOperation(value = "模拟导入设施")
    public Envelop demoImport(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            HttpServletRequest request) throws IOException, ManageException {
        try {
            request.setCharacterEncoding("UTF-8");
            AExcelReader excelReader = new ImportDemoReader();
            excelReader.read(file);
            List<Map<String,String>> dataList = excelReader.getCorrectLs();
            if (dataList.size() > 0) {
                //TODO 导入
                System.out.println(dataList);
                return success("导入成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed("导入异常,请检查导入文件格式"+e.getMessage());
        }
        return failed("导入失败");
    }
}

+ 12 - 5
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/FacilityUsedRecordController.java

@ -129,9 +129,9 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
        FacilityUsedRecord facilityUsedRecord;
        if (nearbyFlag) {
            if (StringUtils.isNotEmpty(filters)) {
                filters =  "deleteFlag=0;status=0;"+"name?" + filters + " g1;cityName?" + filters + " g1;countyName?" + filters + " g1;street?" + filters + " g1;address?"  + filters + " g1;";
            }else{
                filters =  "deleteFlag=0;status=0;";
                filters = "deleteFlag=0;status=0;" + "name?" + filters + " g1;cityName?" + filters + " g1;countyName?" + filters + " g1;street?" + filters + " g1;address?" + filters + " g1;";
            } else {
                filters = "deleteFlag=0;status=0;";
            }
            //获取所有设施,并根据设施编码及用户id查找使用次数
            List<Facility> facilityList = facilityService.search(filters);
@ -145,6 +145,7 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
                facilityUsedRecord.setCreateUser(userId);
                facilityUsedRecord.setUserId(userId);
                facilityUsedRecord.setFacilitieId(facility.getId());
                facilityUsedRecord.setFacilitieStatus(facility.getStatus());
                long count = facilityUsedRecordService.countByFacilitieCodeAndUserId(facility.getCode(), userId);
                facilityUsedRecord.setNum((int) count);
                facilityUsedRecordList.add(facilityUsedRecord);
@ -155,6 +156,9 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
            for (FacilityUsedRecord facilityUsedRecord1 : facilityUsedRecordList) {
                long count = facilityUsedRecordService.countByFacilitieCodeAndUserId(facilityUsedRecord1.getFacilitieCode(), userId);
                facilityUsedRecord1.setNum((int) count);
                //获取设施状态
                Facility facility = facilityService.findByCode(facilityUsedRecord1.getFacilitieCode());
                facilityUsedRecord1.setFacilitieStatus(facility.getStatus());
            }
        }
        return success(facilityUsedRecordList);
@ -183,14 +187,14 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
    public ObjEnvelop facilityUsedRecordDetail(
            @ApiParam(name = "id", value = "使用记录ID", defaultValue = "")
            @RequestParam(value = "id") String id) throws Exception {
        if (id == null ){
        if (id == null) {
            throw new ManageException("使用记录ID为空!");
        }
        Map<String, Object> usedRecordDetail = facilityUsedRecordService.getUsedRecordDetail(id);
        return success(usedRecordDetail);
    }
    @ApiOperation(value = "获取用户使用导航记录列表--分页(app)", responseContainer = "List")
    @ApiOperation(value = "我的行程-获取用户使用导航记录列表--分页(app)", responseContainer = "List")
    @GetMapping(value = HealthyHouseMapping.HealthyHouse.FacilityUsedRecord.PAGE_FACILITY_USED_RECORD_BY_USERID)
    public PageEnvelop<FacilityUsedRecord> getFacilityUsedRecordsByUserId(
            @ApiParam(name = "userId", value = "必输参数:登录用户id", defaultValue = "")
@ -217,6 +221,9 @@ public class FacilityUsedRecordController extends EnvelopRestEndpoint {
            } else {
                record.setNavigationServiceEvaluationFlag("已评价");
            }
            //根据设施编码获取 设施状态
            Facility facility = facilityService.findByCode(facilityCode);
            record.setFacilitieStatus(facility.getStatus());
        }
        int count = (int) facilityUsedRecordService.getCount(filters);
        return success(facilityUsedRecordList, count, page, size);

+ 14 - 13
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/UserController.java

@ -173,7 +173,7 @@ public class UserController extends EnvelopRestEndpoint {
        try {
            User user = userService.findByTelephoneAndUserType(newPhone, LoginInfo.USER_TYPE_PATIENT);
            if (user == null) {
            if (user != null) {
                return failed("手机号:" + newPhone + "已被绑定,可更换新手机号或直接登录!");
            }
            //验证码
@ -198,7 +198,7 @@ public class UserController extends EnvelopRestEndpoint {
        try {
            User user = userService.findByTelephoneAndUserType(newPhone, LoginInfo.USER_TYPE_SUPER_AdminManager);
            if (user == null) {
            if (user != null) {
                return failed("手机号:" + newPhone + "已被绑定,可更换新手机号或直接登录!");
            }
            //验证码
@ -280,27 +280,28 @@ public class UserController extends EnvelopRestEndpoint {
    @ApiOperation(value = "用户列表导出excel")
    public Envelop exportToExcel(
            HttpServletResponse response,
            @ApiParam(name = "city", value = "所在市区", required = false) @RequestParam(required = false, name = "city") String city,
            @ApiParam(name = "activated", value = "用户状态", required = false) @RequestParam(required = false, name = "activated") String activated,
            @ApiParam(name = "name", value = "姓名/手机号", required = false) @RequestParam(required = false, name = "name") String name,
            @ApiParam(name = "sort", value = "使用次数排序", required = false) @RequestParam(required = false, name = "sort") String sort) {
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts) {
        response.setCharacterEncoding("UTF-8");
        try {
            //获取用户数据
            Map<String, String> map = new HashMap<>();
            map.put("cityCode", city);
            map.put("activated", activated);
            map.put("name", name);
            map.put("telephone", name);
            List<User> userList = userService.userList(map, sort);
            List<User> userList = userService.search(fields, filters, sorts);
            userService.exportUsersExcel(response, userList);
            return success("导出成功");
        } catch (ManageException e) {
            return failed(e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @PostMapping(value = "/heartbeat")
    @ApiOperation(value = "用户在线-心跳接口", notes = "心跳接口")
    public Envelop heartbeat(
@ -308,7 +309,7 @@ public class UserController extends EnvelopRestEndpoint {
            @RequestParam(value = "userId") String userId) {
        try {
            userService.setUserActivated(userId, 10);
            userService.setUserActivated(userId, 40);//客户端30s发送一次心跳,
            return success("心跳正常");
        } catch (Exception e) {
            return failed("心跳异常");

+ 12 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/dao/user/UserDao.java

@ -7,7 +7,9 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
 * @author HZY
@ -45,4 +47,14 @@ public interface UserDao extends PagingAndSortingRepository<User, String>, JpaSp
    User findByUserTypeAndTelephoneOrLoginCode(String userType,String telephone,String loginCode);
    User findByTelephoneAndUserType(String telephone,String userType);
    @Transactional
    @Modifying
    @Query("update User u set u.activated = 2 where u.activated = 1 and u.id not in ?1")
    void updateUserOffLine(List<Serializable> ids);
    @Transactional
    @Modifying
    @Query("update User u set u.activated = 1 where u.activated = 2 and u.id in ?1")
    void updateUserOnLine(List<Serializable> ids);
}

+ 157 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/interceptor/ActivatedInterceptor.java

@ -0,0 +1,157 @@
package com.yihu.jw.healthyhouse.interceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.healthyhouse.constant.LoginInfo;
import com.yihu.jw.healthyhouse.model.user.User;
import com.yihu.jw.healthyhouse.service.user.UserService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import net.sf.json.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
 *  用户在线状态验证拦截器
 * @author HZY
 * @created 2018/10/9 9:19
 */
//@Aspect
//@Component
public class ActivatedInterceptor  {
    private static final Logger logger = LoggerFactory.getLogger(ActivatedInterceptor.class);
    @Autowired
    private UserService userService;
//    @Around("execution(* com.yihu.jw.healthyhouse.controller..*.*(..))")
//    public Object logAround(ProceedingJoinPoint  joinPoint) throws Throwable{
//        ObjectMapper objectMapper = new ObjectMapper();
//        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
//        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//        HttpServletRequest request = sra.getRequest();
//        HttpSession session = request.getSession();
//        String method = request.getMethod();
//        String queryString = request.getQueryString();
//
//        String classType = joinPoint.getTarget().getClass().getName();
//        Class<?> clazz = Class.forName(classType);
//        String clazzName = clazz.getName();
//        String methodName = joinPoint.getSignature().getName(); //获取方法名称
//        Object[] args = joinPoint.getArgs();//参数
//
//        String params = "";
//        //获取请求参数集合并进行遍历拼接
//        if(args.length>0){
//            if("POST".equals(method)){
//                Object object = args[0];
//                Map map = getFieldsName(this.getClass(), clazzName, methodName,args);
//                params = objectMapper.writeValueAsString(map);
//            }else if("GET".equals(method)){
//                Map<String, String[]> parameterMap = request.getParameterMap();
//                params = objectMapper.writeValueAsString(parameterMap);;
//            }
//        }
//        //获取参数名称和值
////        Map<String,Object > nameAndArgs = getFieldsName(this.getClass(), clazzName, methodName,args);
//        System.out.println(params);
//        return  joinPoint.proceed();
//
//    }
    @Around("execution(* com.yihu.jw.healthyhouse.controller..*.*(..))")
    public Object activatedAround(ProceedingJoinPoint  joinPoint) throws Throwable{
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        HttpServletResponse response = sra.getResponse();
        HttpSession session = request.getSession();
        Object userId = session.getAttribute(LoginInfo.USER_ID);
        if (userId == null ){
            response.setStatus(402);
            return  joinPoint.proceed();
//            return failed("用户未登录,请登录!",-10000);
        }
        User user = userService.findById(userId.toString());
        if (user == null ){
            response.setStatus(402);
            return  joinPoint.proceed();
//            return failed("用户不存在,请重新登录!",-10000);
        }else if (HouseUserContant.activated_lock.equals(user.getActivated())){
            response.setStatus(402);
//           return failed("用户已被冻结,请联系管理员!",-10000);
        }else if (HouseUserContant.activated_offline.equals(user.getActivated())){
            response.setStatus(402);
//            return failed("用户已离线,请重新登录!",-10000);
        }else {
//            return  joinPoint.proceed();
        }
        return  joinPoint.proceed();
    }
    private Map<String, Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
        Map<String, Object> map = new HashMap<String, Object>();
        ClassPool pool = ClassPool.getDefault();
        //ClassClassPath classPath = new ClassClassPath(this.getClass());
        ClassClassPath classPath = new ClassClassPath(cls);
        pool.insertClassPath(classPath);
        CtClass cc = pool.get(clazzName);
        CtMethod cm = cc.getDeclaredMethod(methodName);
        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        if (attr == null) {
            // exception
        }
        // String[] paramNames = new String[cm.getParameterTypes().length];
        int pos = Modifier.isStatic(cm.getModifiers()) ? 1 : 2;
        for (int i = 0; i < cm.getParameterTypes().length; i++) {
            map.put(attr.variableName(i + pos), args[i]);//paramNames即参数名
        }
        return map;
    }
    protected Envelop failed (String message, int status) {
        Envelop envelop = new Envelop();
        envelop.setMessage(message);
        envelop.setStatus(status);
        return envelop;
    }
}

+ 49 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/job/ActivatedUserUpdateTask.java

@ -0,0 +1,49 @@
package com.yihu.jw.healthyhouse.job;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.healthyhouse.service.user.UserService;
import com.yihu.jw.healthyhouse.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.*;
/**
 * Task - 定时检查集群状态,提高解析任务容错率
 * Created by progr1mmer on 2017/12/15.
 */
//@Component
public class ActivatedUserUpdateTask {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private UserService userService;
    @Scheduled(cron = "0/40 * * * * ?")
    private void startTask() {
        List<String> keys = new ArrayList<>();
        String pattern = "healthyHouse:*:activated";
        Set<String> keys1 = redisClient.keys(pattern);
        List<Serializable> ids = redisClient.multiGet(keys1);
        try {
            if (ids!=null && ids.size()>0) {
                userService.updateUserOffLine(ids);
            }
        } catch (ManageException e) {
            e.printStackTrace();
        }
    }
}

+ 1 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/listener/RedisKeyExpirationListener.java

@ -5,6 +5,7 @@ import org.springframework.data.redis.listener.KeyExpirationEventMessageListener
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
 *  redis key 过期通知监听
 * @author HZY
 * @created 2018/10/8 15:11
 */

+ 16 - 1
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/FacilityUsedRecord.java

@ -11,6 +11,7 @@ import java.util.List;
/**
 * 用户导航记录
 *
 * @author zdm
 * @version 1.0
 * @created 2018.09.21
@ -65,6 +66,9 @@ public class FacilityUsedRecord extends UuidIdentityEntityWithOperator {
    //设施关联的服务名称
    private String facilityRelationServiceName;
    //设施状态
    private String facilitieStatus;
    //评价记录
    private String navigationServiceEvaluationFlag;
@ -179,14 +183,16 @@ public class FacilityUsedRecord extends UuidIdentityEntityWithOperator {
    public void setFacilitieId(String facilitieId) {
        this.facilitieId = facilitieId;
    }
    @Transient
    public String getFacilityRelationServiceName() {
        return facilityRelationServiceName;
    }
    public void setFacilityRelationServiceName(String facilityRelationServiceName) {
        this.facilityRelationServiceName =facilityRelationServiceName;
        this.facilityRelationServiceName = facilityRelationServiceName;
    }
    @Transient
    public String getNavigationServiceEvaluationFlag() {
        return navigationServiceEvaluationFlag;
@ -195,4 +201,13 @@ public class FacilityUsedRecord extends UuidIdentityEntityWithOperator {
    public void setNavigationServiceEvaluationFlag(String navigationServiceEvaluationFlag) {
        this.navigationServiceEvaluationFlag = navigationServiceEvaluationFlag;
    }
    @Transient
    public String getFacilitieStatus() {
        return facilitieStatus;
    }
    public void setFacilitieStatus(String facilitieStatus) {
        this.facilitieStatus = facilitieStatus;
    }
}

+ 13 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/User.java

@ -46,6 +46,8 @@ public class User extends UuidIdentityEntityWithOperator {
    private String activatedContent;       //账户冻结原因
    @Column(name = "province_code", nullable = false)
    private String provinceCode;    //省编码
    @Column(name = "province_name", nullable = false)
    private String provinceName;    //省名称
    @Column(name = "city_code", nullable = false)
    private String cityCode;        //市编码
    @Column(name = "city_name", nullable = false)
@ -277,6 +279,9 @@ public class User extends UuidIdentityEntityWithOperator {
    @Transient
    public String getAddress() {
        String address = "";
        if (this.getProvinceName() != null) {
            address += this.getProvinceName();
        }
        if (this.getCityName() != null) {
            address += this.getCityName();
        }
@ -301,4 +306,12 @@ public class User extends UuidIdentityEntityWithOperator {
        }
        return genderValue;
    }
    public String getProvinceName() {
        return provinceName;
    }
    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }
}

+ 71 - 2
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/facility/FacilityService.java

@ -6,8 +6,10 @@ import com.yihu.jw.healthyhouse.model.facility.Facility;
import com.yihu.jw.healthyhouse.service.area.BaseCityService;
import com.yihu.jw.healthyhouse.service.area.BaseTownService;
import com.yihu.jw.healthyhouse.service.dict.SystemDictEntryService;
import com.yihu.jw.healthyhouse.util.RestTemplateUtil;
import com.yihu.jw.healthyhouse.util.facility.msg.FacilityMsg;
import com.yihu.jw.healthyhouse.util.poi.ExcelUtils;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.mysql.query.BaseJpaService;
import jxl.write.Colour;
import jxl.write.WritableCellFormat;
@ -20,6 +22,7 @@ import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -52,6 +55,7 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
    private SystemDictEntryService systemDictEntryService;
    public Facility findById(String id) {
        return facilityDao.findById(id);
    }
@ -101,6 +105,7 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
        try {
            String fileName = "健康小屋-设施列表";
            //设置下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xlsx");
@ -127,7 +132,7 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
                ExcelUtils.addCellData(sheet, 0, row, j + 1 + "");//序号
                ExcelUtils.addCellData(sheet, 1, row, metaData.getCode());//设施编码
                ExcelUtils.addCellData(sheet, 2, row, metaData.getName());//设施名称
                ExcelUtils.addCellData(sheet, 3, row, metaData.getCategory().toString());//类型名称
                ExcelUtils.addCellData(sheet, 3, row, metaData.getCategoryValue());//类型名称
                ExcelUtils.addCellData(sheet, 4, row, metaData.getAddress());//信息地址
                ExcelUtils.addCellData(sheet, 5, row, metaData.getUserName());//联系人
                ExcelUtils.addCellData(sheet, 6, row, metaData.getUserTelephone());//联系电话
@ -135,7 +140,7 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
                ExcelUtils.addCellData(sheet, 8, row, metaData.getCityName());//市
                ExcelUtils.addCellData(sheet, 9, row, metaData.getCountyName());//区县
                ExcelUtils.addCellData(sheet, 10, row, metaData.getStreet());//街道
                ExcelUtils.addCellData(sheet, 11, row, metaData.getStatus());//运营状态
                ExcelUtils.addCellData(sheet, 11, row, metaData.getStatusName());//运营状态
            }
@ -273,5 +278,69 @@ public class FacilityService extends BaseJpaService<Facility, FacilityDao> {
        }
    }
    public Facility findByCode(String code) {
        return facilityDao.findByCode(code);
    }
    /**
     * 批量导入设施的集合
     *
     * @param facilities 设施列表
     */
    public Map<String, Object> batchInsertDemo(List<Map<String,String> > facilities) throws ManageException {
        Map<String, Object> result = new HashMap<>();
        //批量存储的集合
        int correctCount = 0;
        List<Facility> corrects = new ArrayList<>();
        List<Facility> errors = new ArrayList<>();
        Facility facility = null;
        //批量存储
        for (Map<String,String> facilityMsg : facilities) {
            facility = new Facility();
            facility.setCode(genFacilityCode());
            facility.setName(facilityMsg.get("street")+"_健康小屋");
            facility.setCategory(1);
            facility.setCategoryValue("健康小屋");
            facility.setProvinceId("350000");
            facility.setCityCode("350200");
            facility.setCityName("厦门市");
            facility.setCountyCode(baseTownService.getCodeByname(facilityMsg.get("county")));
            facility.setCountyName(facilityMsg.get("county"));
            facility.setStreet(facilityMsg.get("street"));
            if (!facilityMsg.get("address").contains("厦门市")) {
                facility.setAddress("厦门市" + facilityMsg.get("address"));
            }else {
                facility.setAddress(facilityMsg.get("address"));
            }
            facility.setStatus("0");
            if (corrects.size() > 100) {
                facilityDao.save(corrects);
                correctCount += corrects.size();
                corrects.clear();
            }
        }
        if (!corrects.isEmpty()) {
            facilityDao.save(corrects);
            correctCount += corrects.size();
        }
        result.put("correctCount", correctCount);
        result.put("errors", errors);
        return result;
    }
    public Envelop getLatAndlon(String address) {
        Map<String ,String> map = new HashMap<>();
        String url = "http://api.map.baidu.com/geocoder/v2/?address="+ address + "&output=json&ak=465443b4e84fb6823359e5921915e8dc&callback=showLocation";
        RestTemplateUtil restTemplateUtil = new RestTemplateUtil(url,null);
        Envelop envelop = restTemplateUtil.exchange(url, HttpMethod.GET, Envelop.class,map);
        return envelop;
    }
}

+ 18 - 5
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/UserService.java

@ -30,6 +30,7 @@ import org.springside.modules.persistence.SearchFilter;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;
@ -397,14 +398,11 @@ public class UserService extends BaseJpaService<User, UserDao> {
        try {
            String fileName = "健康小屋-用户列表";
            //设置下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" )+".xlsx");
            OutputStream os = response.getOutputStream();
            //获取导出数据集
            JSONObject order = new JSONObject();
            order.put("id","asc");
            //写excel
            Workbook workbook = new XSSFWorkbook();
            int k=0;
@ -426,7 +424,7 @@ public class UserService extends BaseJpaService<User, UserDao> {
                ExcelUtils.addCellData(sheet,2,row, metaData.getLoginCode());//登录名
                ExcelUtils.addCellData(sheet,3,row, metaData.getName());//名称
                ExcelUtils.addCellData(sheet,4,row, metaData.getIdCardNo());//身份证
                ExcelUtils.addCellData(sheet,5,row, metaData.getGender());//性别
                ExcelUtils.addCellData(sheet,5,row, metaData.getGenderValue());//性别
                ExcelUtils.addCellData(sheet,6,row, metaData.getTelephone());//电话
                ExcelUtils.addCellData(sheet,7,row, metaData.getAddress());//地区
                ExcelUtils.addCellData(sheet,8,row, metaData.getFacilityUsedCount().toString());//使用设施次数
@ -458,6 +456,21 @@ public class UserService extends BaseJpaService<User, UserDao> {
        userDao.save(user1);
    }
    /**
     * 更新用户在线状态
     * @param ids
     * @throws ManageException
     */
    @Transactional
    public void updateUserOffLine(List<Serializable> ids) throws ManageException {
        userDao.updateUserOnLine(ids);//更新在线
        userDao.updateUserOffLine(ids);//更新离线
    }
}

+ 71 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/ImportDemoReader.java

@ -0,0 +1,71 @@
package com.yihu.jw.healthyhouse.util;
import com.yihu.jw.healthyhouse.util.facility.msg.FacilityMsg;
import com.yihu.jw.healthyhouse.util.poi.AExcelReader;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
 *  设施列表-excel解析类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2018/9/25.
 */
public class ImportDemoReader extends AExcelReader {
    @Override
    public void read(Workbook rwb) throws Exception {
        try {
            Iterator<Sheet> sheets = rwb.sheetIterator();
            int j = 0, rows;
            Map<String,String> facilityMsg;
            while (sheets.hasNext()){
                Sheet sheet = sheets.next();
                if ((rows = sheet.getLastRowNum()) == 0) {
                    continue;
                }
                for (int i = 1; i <= rows; i++) {
                    facilityMsg = new HashMap<>();
                    //区
                    if(null != getCellCont(sheet, i, 1)){
                        //去除空格、回车、换行、制表符
                        facilityMsg.put("county",replaceBlank(getCellCont(sheet, i, 1)));
                    }else{
                        facilityMsg.put("county",getCellCont(sheet, i, 1));
                    }
                    //设施类型名称
                    if(null != getCellCont(sheet, i, 2)){
                        //去除空格、回车、换行、制表符
                        facilityMsg.put("street",replaceBlank(getCellCont(sheet, i, 2)));
                    }else{
                        facilityMsg.put("street",getCellCont(sheet, i, 2));
                    }
                    facilityMsg.put("service",getCellCont(sheet, i, 3));//服务
                    facilityMsg.put("address",getCellCont(sheet, i, 4));//详细地址
                    correctLs.add(facilityMsg);
                }
                j++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (rwb != null) {
                rwb.close();
            }
        }
    }
}

+ 167 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/RedisClient.java

@ -0,0 +1,167 @@
package com.yihu.jw.healthyhouse.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.SerializationUtils;
import java.io.Serializable;
import java.util.*;
/**
 * Redis 数据访问接口。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.08.04 11:12
 */
@Service
public class RedisClient {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    /**
     * 添加数据。
     *
     * @param key
     * @param value
     */
    public void set(final String key, final Serializable value) {
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] key_ = key.getBytes();
            byte[] value_ = SerializationUtils.serialize(value);
            connection.set(key_, value_);
            return true;
        });
    }
    /**
     * 添加数据,含失效时间。
     *
     * @param key
     * @param value
     */
    public void set(final String key, final Serializable value,long seconds) {
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] key_ = key.getBytes();
            byte[] value_ = SerializationUtils.serialize(value);
            connection.setEx(key_,seconds, value_);
            return true;
        });
    }
    /**
     * 批量设置key-value值。
     *
     * @param data
     */
    public void multiSet(Map<Serializable, Serializable> data){
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
                for(Serializable key : data.keySet()){
                    Serializable value = data.get(key);
                    connection.rPushX(SerializationUtils.serialize(key), SerializationUtils.serialize(value));
                }
                return null;
            }
        });
    }
    /**
     * 批量设置key-value值。
     *
     * @param data
     */
    public void multiSetData(Map<String, Serializable> data){
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                for (String key : data.keySet()) {
                    byte[] key_ = key.getBytes();
                    byte[] value_ = SerializationUtils.serialize(data.get(key));
                    connection.setNX(key_, value_);
                }
                return null;
            }
        });
    }
    /**
     * 获取数据
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> T get(final String key) {
        return (T)redisTemplate.execute((RedisCallback<Serializable>) connection -> {
            byte[] keyBytes = key.getBytes();
            byte[] bytes = connection.get(keyBytes);
            if(bytes == null) return null;
            return (Serializable) SerializationUtils.deserialize(bytes);
        });
    }
    /**
     * 批量获取key关联的值。
     *
     * @param keys
     * @return
     */
    public List<Serializable> multiGet(Collection<String> keys){
        return redisTemplate.opsForValue().multiGet(keys);
    }
    /**
     * 删除记录,支持Key模糊匹配删除
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(redisTemplate.keys(key));
    }
    /**
     * 删除多条记录,如果Key集合过大,建议使用Key模糊匹配删除
     * @param keys
     */
    public void delete(Collection<String> keys) {
        redisTemplate.delete(keys);
    }
    /**
     * 匹配特定模式的Key列表
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<byte[]> keys = connection.keys(pattern.getBytes());
            Set<String> returnKeys = new HashSet<>();
            for (byte[] key : keys) {
                returnKeys.add(new String(key));
            }
            return returnKeys;
        });
    }
    /**
     * 是否包含指定Key
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.exists(SerializationUtils.serialize(key)));
    }
}

+ 127 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/util/RestTemplateUtil.java

@ -0,0 +1,127 @@
package com.yihu.jw.healthyhouse.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.nio.charset.Charset;
import java.util.Map;
/**
 * Created by Administrator on 2017/6/15 0015.
 */
public class RestTemplateUtil {
    private String url;
    private MultiValueMap<String, String> params ;
    public void set(String key, String value) {
        params.add(key, value);
    }
    /**
     * 构造方法,请求url.
     *
     * @param url 请求地址
     */
    public RestTemplateUtil(String url) {
        super();
        this.url = url;
    }
    public RestTemplateUtil(String url, MultiValueMap<String, String> params) {
        super();
        this.url = url;
        this.params = params;
    }
    /**
     * 发送get请求.
     *
     * @return 返回请求结果
     */
    public <T> T get(Class<T> cls) {
        String fullUrl = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build().toUriString();
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity =  restTemplate.getForEntity(fullUrl, cls);
        return resultEntity.getBody();
    }
    /**
     * 发送post请求.
     *
     * @return 返回请求结果
     */
    public <T> T post(Class<T> cls) {
        String fullUrl = UriComponentsBuilder.fromHttpUrl(url).build().toUriString();
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.postForEntity(fullUrl, params, cls);
        return resultEntity.getBody();
    }
    /**
     * 发送/获取 服务端数据(主要用于解决发送put,delete方法无返回值问题).
     *
     * @param url      绝对地址
     * @param method   请求方式
     * @param bodyType 返回类型
     * @param <T>      返回类型
     * @return 返回结果(响应体)
     */
    public <T> T exchange(String url, HttpMethod method, Class<T> bodyType) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        //提供json转化功能
        ObjectMapper mapper = new ObjectMapper();
        String str = null;
        try {
            if (params!=null&&!params.isEmpty()) {
                str = mapper.writeValueAsString(params);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(str, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, bodyType);
        return resultEntity.getBody();
    }
    public <T> T exchange(String url, HttpMethod method, Class<T> bodyType,Map<String ,?> map) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        //提供json转化功能
        ObjectMapper mapper = new ObjectMapper();
        String str = null;
        try {
            if (params!=null&&!params.isEmpty()) {
                str = mapper.writeValueAsString(params);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(str, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, bodyType,map);
        return resultEntity.getBody();
    }
}

+ 4 - 0
svr/svr-healthy-house/src/main/resources/application.yml

@ -7,6 +7,10 @@ security:
    enabled: false
spring:
  http:
    multipart:
      maxRequestSize: 1024MB  #配置最大上传为1G
      maxFileSize: 1024MB  #配置最大上传为1G
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 50