Jelajahi Sumber

Merge branch 'dev' of LiTaohong/jw2.0 into dev

chenweida 7 tahun lalu
induk
melakukan
c5e36f96b8
37 mengubah file dengan 2501 tambahan dan 40 penghapusan
  1. TEMPAT SAMPAH
      Swisin.SDTC.Service 应用手册.doc
  2. TEMPAT SAMPAH
      Swisin.SDTC.Service主程序.zip
  3. 29 0
      base/common-cache/pom.xml
  4. 96 0
      base/common-cache/src/main/java/com/yihu/base/cache/cache/CustomMapCache.java
  5. 150 0
      base/common-cache/src/main/java/com/yihu/base/cache/cache/CustomRedisCache.java
  6. 21 0
      base/common-cache/src/main/java/com/yihu/base/cache/config/CacheKeyGenerator.java
  7. 315 0
      base/common-cache/src/main/java/com/yihu/base/cache/lock/CacheLock.java
  8. 29 0
      base/common-cache/src/main/java/com/yihu/base/cache/manager/CacheManagerFactory.java
  9. 25 0
      base/common-cache/src/main/java/com/yihu/base/cache/manager/CustomCacheManager.java
  10. 149 0
      base/common-cache/src/main/java/com/yihu/base/cache/manager/CustomMapCacheManager.java
  11. 182 0
      base/common-cache/src/main/java/com/yihu/base/cache/manager/CustomRedisCacheManager.java
  12. 75 0
      base/common-cache/src/main/java/com/yihu/base/cache/support/CacheInvocation.java
  13. 33 0
      base/common-cache/src/main/java/com/yihu/base/cache/support/CacheSupport.java
  14. 88 0
      base/common-cache/src/main/java/com/yihu/base/cache/support/CacheSupportImpl.java
  15. 83 0
      base/common-cache/src/main/java/com/yihu/base/cache/support/CachingAnnoationAspect.java
  16. 64 0
      base/common-cache/src/main/java/com/yihu/base/cache/support/MapCacheSupportImpl.java
  17. 60 0
      base/common-cache/src/main/java/com/yihu/base/cache/support/RedisCacheSupportImpl.java
  18. 34 0
      base/common-cache/src/main/java/com/yihu/base/cache/util/RedisTemplateUtils.java
  19. 145 0
      base/common-cache/src/main/java/com/yihu/base/cache/util/ReflectionUtils.java
  20. 68 0
      base/common-cache/src/main/java/com/yihu/base/cache/util/SpringContextUtils.java
  21. 32 0
      base/common-cache/src/main/java/com/yihu/base/cache/util/ThreadTaskUtils.java
  22. 17 0
      base/common-cache/src/main/resources/template.yml
  23. 5 5
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseUserRequestMapping.java
  24. 175 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/user/BaseEmployVO.java
  25. 85 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/user/BaseMenuVO.java
  26. 50 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/user/BaseRoleVO.java
  27. 5 0
      svr/svr-base/pom.xml
  28. 117 3
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseRoleController.java
  29. 129 9
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployController.java
  30. 6 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleMenuDao.java
  31. 3 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployDao.java
  32. 6 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployRoleDao.java
  33. 63 9
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleMenuService.java
  34. 53 5
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployRoleService.java
  35. 29 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployService.java
  36. 60 3
      web-gateway/src/main/java/com/yihu/jw/controller/base/user/EmployController.java
  37. 20 6
      web-gateway/src/main/java/com/yihu/jw/feign/base/user/EmployFeign.java

TEMPAT SAMPAH
Swisin.SDTC.Service 应用手册.doc


TEMPAT SAMPAH
Swisin.SDTC.Service主程序.zip


+ 29 - 0
base/common-cache/pom.xml

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.base</groupId>
        <artifactId>common-lib-parent-pom</artifactId>
        <version>1.0.0</version>
        <relativePath>../../common-lib-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>common-customCache</groupId>
    <artifactId>common-customCache</artifactId>
    <version>1.0.0</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.10</version>
        </dependency>
    </dependencies>
    
</project>

+ 96 - 0
base/common-cache/src/main/java/com/yihu/base/cache/cache/CustomMapCache.java

@ -0,0 +1,96 @@
package com.yihu.base.cache.cache;
import com.yihu.base.cache.config.CacheKeyGenerator;
import com.yihu.base.cache.lock.CacheLock;
import com.yihu.base.cache.support.CacheSupport;
import com.yihu.base.cache.util.ReflectionUtils;
import com.yihu.base.cache.util.SpringContextUtils;
import com.yihu.base.cache.util.ThreadTaskUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.cache.RedisCacheElement;
import org.springframework.data.redis.cache.RedisCacheKey;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class CustomMapCache extends ConcurrentMapCache{
    private Long expireTime;
    private Long refreshTime;
    private Long startTime;
    public Long getStartTime() {
        return startTime;
    }
    public CustomMapCache(String name) {
        super(name);
    }
    public Long getExpireTime() {
        return expireTime;
    }
    public Long getRefreshTime() {
        return refreshTime;
    }
    public CustomMapCache(String name,Long expireTime, Long refreshTime){
        super(name);
        this.expireTime = expireTime;
        this.refreshTime = refreshTime;
        this.startTime = System.currentTimeMillis();
    }
    private CacheSupport getCacheSupport() {
        return SpringContextUtils.getBean(CacheSupport.class);
    }
    /**
     * 重写get方法,获取到缓存后再次取缓存剩余的时间,如果时间小余我们配置的刷新时间就手动刷新缓存,对于内存缓存,直接移除
     * @param key
     * @return
     */
    @Override
    public ValueWrapper get(Object key) {
        String cacheKey = CacheKeyGenerator.getCacheKey();
        ValueWrapper valueWrapper = this.get(key);
        if (null != valueWrapper) {
            // 刷新缓存数据
            refreshCache(key,cacheKey);
        }
        return valueWrapper;
    }
    /**
     * 刷新缓存数据
     */
    private void refreshCache(Object key, String cacheKeyStr) {
        ConcurrentMap<Object, Object> cacheMap = (ConcurrentMap<Object, Object>) ReflectionUtils.getFieldValue(ConcurrentMapCache.class, "store");
        CustomMapCache customMapCache = (CustomMapCache) cacheMap.get(key);
        Long diffTime = System.currentTimeMillis() - customMapCache.getStartTime();
        if (diffTime >= customMapCache.getExpireTime() || diffTime <= customMapCache.getRefreshTime()) {
            synchronized (cacheMap){
                if (diffTime <= customMapCache.getRefreshTime()) {
                    // 通过获取代理方法信息重新加载缓存数据
                    CustomMapCache.this.getCacheSupport().refreshCacheByKey(customMapCache.getName(), key.toString());
                }
            }
        }
    }
}

+ 150 - 0
base/common-cache/src/main/java/com/yihu/base/cache/cache/CustomRedisCache.java

@ -0,0 +1,150 @@
package com.yihu.base.cache.cache;
import com.yihu.base.cache.config.CacheKeyGenerator;
import com.yihu.base.cache.support.CacheSupport;
import com.yihu.base.cache.lock.CacheLock;
import com.yihu.base.cache.util.SpringContextUtils;
import com.yihu.base.cache.util.ThreadTaskUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheElement;
import org.springframework.data.redis.cache.RedisCacheKey;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
public class CustomRedisCache extends RedisCache{
    private Long expireTime;
    private Long refreshTime;
    private RedisOperations redisOperations;
    private CacheSupport getCacheSupport() {
        return SpringContextUtils.getBean(CacheSupport.class);
    }
    private byte[] prefix;
    public CustomRedisCache(String name, byte[] prefix, RedisOperations<?, ?> redisOperations, long expiration) {
        super(name, prefix, redisOperations, expiration);
    }
    public CustomRedisCache(String name, byte[] prefix, RedisOperations<? extends Object, ? extends Object> redisOperations, long expiration, long refreshTime) {
        super(name, prefix, redisOperations, expiration);
        this.redisOperations = redisOperations;
        this.refreshTime = refreshTime;
        this.prefix = prefix;
    }
    public CustomRedisCache(String name, byte[] prefix, RedisOperations<? extends Object, ? extends Object> redisOperations, long expiration, long refreshTime, boolean allowNullValues) {
        super(name, prefix, redisOperations, expiration, allowNullValues);
        this.redisOperations = redisOperations;
        this.refreshTime = refreshTime;
        this.prefix = prefix;
    }
    /**
     * 重写get方法,获取到缓存后再次取缓存剩余的时间,如果时间小余我们配置的刷新时间就手动刷新缓存。
     * 为了不影响get的性能,启用后台线程去完成缓存的刷新
     * 并且只开一个线程去刷新数据。
     * @param key
     * @return
     */
    @Override
    public ValueWrapper get(Object key) {
        String cacheKey = CacheKeyGenerator.getCacheKey();
        ValueWrapper valueWrapper = this.get(cacheKey);
        if (null != valueWrapper) {
            // 刷新缓存数据
            refreshCache(key, cacheKey);
        }
        return valueWrapper;
    }
    /**
     * 重写父类的get函数。
     * 父类的get方法,是先使用exists判断key是否存在,不存在返回null,存在再到redis缓存中去取值。这样会导致并发问题,
     * 假如有一个请求调用了exists函数判断key存在,但是在下一时刻这个缓存过期了,或者被删掉了。
     * 这时候再去缓存中获取值的时候返回的就是null了。
     * 可以先获取缓存的值,再去判断key是否存在。
     *
     * @param cacheKey
     * @return
     */
    @Override
    public RedisCacheElement get(final RedisCacheKey cacheKey) {
        Assert.notNull(cacheKey, "CacheKey must not be null!");
        // 根据key获取缓存值
        RedisCacheElement redisCacheElement = new RedisCacheElement(cacheKey, fromStoreValue(lookup(cacheKey)));
        // 判断key是否存在
        Boolean exists = (Boolean) redisOperations.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.exists(cacheKey.getKeyBytes());
            }
        });
        if (!exists.booleanValue()) {
            return null;
        }
        return redisCacheElement;
    }
    /**
     * 刷新缓存数据
     */
    private void refreshCache(Object key, String cacheKeyStr) {
        Long ttl = this.redisOperations.getExpire(cacheKeyStr);
        if (null != ttl && ttl <= CustomRedisCache.this.refreshTime) {
            // 尽量少的去开启线程,因为线程池是有限的
            ThreadTaskUtils.run(new Runnable() {
                @Override
                public void run() {
                    // 加一个分布式锁,只放一个请求去刷新缓存
                    CacheLock cacheLock = new CacheLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock");
                    try {
                        if (cacheLock.lock()) {
                            // 获取锁之后再判断一下过期时间,看是否需要加载数据
                            Long ttl = CustomRedisCache.this.redisOperations.getExpire(cacheKeyStr);
                            if (null != ttl && ttl <= CustomRedisCache.this.refreshTime) {
                                // 通过获取代理方法信息重新加载缓存数据
                                CustomRedisCache.this.getCacheSupport().refreshCacheByKey(CustomRedisCache.super.getName(), key.toString());
                            }
                        }
                    } catch (Exception e) {
                    } finally {
                        cacheLock.unlock();
                    }
                }
            });
        }
    }
    public Long getExpireTime() {
        return expireTime;
    }
    public Long getRefreshTime() {
        return refreshTime;
    }
    public void setExpireTime(Long expireTime) {
        this.expireTime = expireTime;
    }
    public void setRefreshTime(Long refreshTime) {
        this.refreshTime = refreshTime;
    }
}

+ 21 - 0
base/common-cache/src/main/java/com/yihu/base/cache/config/CacheKeyGenerator.java

@ -0,0 +1,21 @@
package com.yihu.base.cache.config;
/**
 * 生成缓存的key
 */
public class CacheKeyGenerator {
    private static String cacheKey;
    public static void setCacheKey(String moduleName,String saasId,String bussinessModuleName) {
        StringBuilder str = new StringBuilder();
        str.append(moduleName + "-");
        str.append(saasId + "-");
        str.append(bussinessModuleName);
        cacheKey = str.toString();
    }
    public static String getCacheKey(){
        return cacheKey;
    }
}

+ 315 - 0
base/common-cache/src/main/java/com/yihu/base/cache/lock/CacheLock.java

@ -0,0 +1,315 @@
package com.yihu.base.cache.lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
/**
 * 缓存锁
 */
public class CacheLock {
    private static Logger logger = LoggerFactory.getLogger(CacheLock.class);
    private RedisTemplate redisTemplate;
    /**
     * 将key 的值设为value ,当且仅当key 不存在,等效于 SETNX。
     */
    public static final String NX = "NX";
    /**
     * seconds — 以秒为单位设置 key 的过期时间,等效于EXPIRE key seconds
     */
    public static final String EX = "EX";
    /**
     * 调用set后的返回值
     */
    public static final String OK = "OK";
    /**
     * 默认请求锁的超时时间(ms 毫秒)
     */
    private static final long TIME_OUT = 100;
    /**
     * 默认锁的有效时间(s)
     */
    public static final int EXPIRE = 60;
    /**
     * 解锁的lua脚本
     */
    public static final String UNLOCK_LUA;
    static {
        StringBuilder sb = new StringBuilder();
        sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
        sb.append("then ");
        sb.append("    return redis.call(\"del\",KEYS[1]) ");
        sb.append("else ");
        sb.append("    return 0 ");
        sb.append("end ");
        UNLOCK_LUA = sb.toString();
    }
    /**
     * 锁标志对应的key
     */
    private String lockKey;
    /**
     * 记录到日志的锁标志对应的key
     */
    private String lockKeyLog = "";
    /**
     * 锁对应的值
     */
    private String lockValue;
    /**
     * 锁的有效时间(s)
     */
    private int expireTime = EXPIRE;
    /**
     * 请求锁的超时时间(ms)
     */
    private long timeOut = TIME_OUT;
    /**
     * 锁标记
     */
    private volatile boolean locked = false;
    final Random random = new Random();
    /**
     * 使用默认的锁过期时间和请求锁的超时时间
     *
     * @param redisTemplate
     * @param lockKey       锁的key(Redis的Key)
     */
    public CacheLock(RedisTemplate redisTemplate, String lockKey) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey + "_lock";
    }
    /**
     * 使用默认的请求锁的超时时间,指定锁的过期时间
     *
     * @param redisTemplate
     * @param lockKey       锁的key(Redis的Key)
     * @param expireTime    锁的过期时间(单位:秒)
     */
    public CacheLock(RedisTemplate redisTemplate, String lockKey, int expireTime) {
        this(redisTemplate, lockKey);
        this.expireTime = expireTime;
    }
    /**
     * 使用默认的锁的过期时间,指定请求锁的超时时间
     *
     * @param redisTemplate
     * @param lockKey       锁的key(Redis的Key)
     * @param timeOut       请求锁的超时时间(单位:毫秒)
     */
    public CacheLock(RedisTemplate redisTemplate, String lockKey, long timeOut) {
        this(redisTemplate, lockKey);
        this.timeOut = timeOut;
    }
    /**
     * 锁的过期时间和请求锁的超时时间都是用指定的值
     *
     * @param redisTemplate
     * @param lockKey       锁的key(Redis的Key)
     * @param expireTime    锁的过期时间(单位:秒)
     * @param timeOut       请求锁的超时时间(单位:毫秒)
     */
    public CacheLock(RedisTemplate redisTemplate, String lockKey, int expireTime, long timeOut) {
        this(redisTemplate, lockKey, expireTime);
        this.timeOut = timeOut;
    }
    /**
     * 尝试获取锁 超时返回
     *
     * @return
     */
    public boolean tryLock() {
        // 生成随机key
        lockValue = UUID.randomUUID().toString();
        // 请求锁超时时间,纳秒
        long timeout = timeOut * 1000000;
        // 系统当前时间,纳秒
        long nowTime = System.nanoTime();
        while ((System.nanoTime() - nowTime) < timeout) {
            if (OK.equalsIgnoreCase(this.set(lockKey, lockValue, expireTime))) {
                locked = true;
                // 上锁成功结束请求
                return locked;
            }
            // 每次请求等待一段时间
            seleep(10, 50000);
        }
        return locked;
    }
    /**
     * 尝试获取锁 立即返回
     *
     * @return 是否成功获得锁
     */
    public boolean lock() {
        lockValue = UUID.randomUUID().toString();
        //不存在则添加 且设置过期时间(单位ms)
        String result = set(lockKey, lockValue, expireTime);
        locked = OK.equalsIgnoreCase(result);
        return locked;
    }
    /**
     * 以阻塞方式的获取锁
     *
     * @return 是否成功获得锁
     */
    public boolean lockBlock() {
        lockValue = UUID.randomUUID().toString();
        while (true) {
            //不存在则添加 且设置过期时间(单位ms)
            String result = set(lockKey, lockValue, expireTime);
            if (OK.equalsIgnoreCase(result)) {
                locked = true;
                return locked;
            }
            // 每次请求等待一段时间
            seleep(10, 50000);
        }
    }
    /**
     * 解锁
     * 不使用固定的字符串作为键的值,而是设置一个不可猜测(non-guessable)的长随机字符串,作为口令串(token)。
     * 不使用 DEL 命令来释放锁,而是发送一个 Lua 脚本,这个脚本只在客户端传入的值和键的口令串相匹配时,才对键进行删除。
     * 这两个改动可以防止持有过期锁的客户端误删现有锁的情况出现。
     */
    public Boolean unlock() {
        // 只有加锁成功并且锁还有效才去释放锁
        if (locked) {
            return (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
                @Override
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    Object nativeConnection = connection.getNativeConnection();
                    Long result = 0L;
                    List<String> keys = new ArrayList<>();
                    keys.add(lockKey);
                    List<String> values = new ArrayList<>();
                    values.add(lockValue);
                    // 集群模式
                    if (nativeConnection instanceof JedisCluster) {
                        result = (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, values);
                    }
                    // 单机模式
                    if (nativeConnection instanceof Jedis) {
                        result = (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, values);
                    }
                    if (result == 0 && !StringUtils.isEmpty(lockKeyLog)) {
                        logger.info("Redis分布式锁,解锁{}失败!解锁时间:{}", lockKeyLog, System.currentTimeMillis());
                    }
                    locked = result == 0;
                    return result == 1;
                }
            });
        }
        return true;
    }
    /**
     * @param key     锁的Key
     * @param value   锁里面的值
     * @param seconds 过去时间(秒)
     * @return
     */
    private String set(final String key, final String value, final long seconds) {
        Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
        return (String) redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                Object nativeConnection = connection.getNativeConnection();
                String result = null;
                if (nativeConnection instanceof JedisCommands) {
                    result = ((JedisCommands) nativeConnection).set(key, value, NX, EX, seconds);
                }
                if (!StringUtils.isEmpty(lockKeyLog) && !StringUtils.isEmpty(result)) {
                    logger.info("获取锁{}的时间:{}", lockKeyLog, System.currentTimeMillis());
                }
                return result;
            }
        });
    }
    /**
     * @param millis 毫秒
     * @param nanos  纳秒
     * @Title: seleep
     * @Description: 线程等待时间
     * @author yuhao.wang
     */
    private void seleep(long millis, int nanos) {
        try {
            Thread.sleep(millis, random.nextInt(nanos));
        } catch (InterruptedException e) {
            logger.info("获取分布式锁休眠被中断:", e);
        }
    }
    public String getLockKeyLog() {
        return lockKeyLog;
    }
    public void setLockKeyLog(String lockKeyLog) {
        this.lockKeyLog = lockKeyLog;
    }
    public int getExpireTime() {
        return expireTime;
    }
    public void setExpireTime(int expireTime) {
        this.expireTime = expireTime;
    }
    public long getTimeOut() {
        return timeOut;
    }
    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }
}

+ 29 - 0
base/common-cache/src/main/java/com/yihu/base/cache/manager/CacheManagerFactory.java

@ -0,0 +1,29 @@
package com.yihu.base.cache.manager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
public class CacheManagerFactory {
    @Value("cache")
    private String caceType;
    public CacheManager getCacheManager(){
        CacheManager cacheManager = null;
        if(StringUtils.isEmpty(caceType)){
            return cacheManager;
        }
        switch (Integer.parseInt(caceType)){
            case 1:
                cacheManager = new CustomMapCacheManager();
                break;
            case 2:
                cacheManager = new CustomRedisCacheManager(new RedisTemplate());
                break;
        }
        return cacheManager;
    }
}

+ 25 - 0
base/common-cache/src/main/java/com/yihu/base/cache/manager/CustomCacheManager.java

@ -0,0 +1,25 @@
package com.yihu.base.cache.manager;
import org.springframework.cache.CacheManager;
public interface CustomCacheManager extends CacheManager{
    /**
     * 注解分隔符
     */
    String SEPARATOR = "#";
    /**
     * SpEL标示符
     */
     String MARK = "$";
    Long getExpireTime();
    Long getRefreshTime();
    Long getExpireTime(String cacheName,String[] cacheParams);
    Long getRefreshTime(String[] cacheParams);
}

+ 149 - 0
base/common-cache/src/main/java/com/yihu/base/cache/manager/CustomMapCacheManager.java

@ -0,0 +1,149 @@
package com.yihu.base.cache.manager;
import com.yihu.base.cache.cache.CustomMapCache;
import com.yihu.base.cache.util.ReflectionUtils;
import com.yihu.base.cache.util.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class CustomMapCacheManager extends ConcurrentMapCacheManager implements CustomCacheManager{
    @Value("expire-time")
    private Long expireTime;
    @Value("refresh-time")
    private Long refreshTime;
    private ConcurrentMapCacheManager concurrentMapCacheManager;
    @Autowired
    private DefaultListableBeanFactory beanFactory;
    private static final String SUPER_CACHEMAP = "cacheMap";
    public ConcurrentMapCacheManager getInstance(){
        if(null == concurrentMapCacheManager){
            concurrentMapCacheManager = SpringContextUtils.getBean(ConcurrentMapCacheManager.class);
        }
        return concurrentMapCacheManager;
    }
    @Override
    public Long getExpireTime() {
        return null;
    }
    @Override
    public Long getRefreshTime() {
        return null;
    }
    /**
     * 获取过期时间
     * @return
     */
    @Override
    public Long getExpireTime(String cacheName, String[] cacheParams) {
        // 有效时间,初始化获取默认的有效时间
        Long expirationSecondTime = null;
        // 设置key有效时间
        if (cacheParams.length > 1) {
            String expirationStr = cacheParams[1];
            if (!StringUtils.isEmpty(expirationStr)) {
                // 支持配置过期时间使用EL表达式读取配置文件时间
                if (expirationStr.contains(MARK)) {
                    expirationStr = beanFactory.resolveEmbeddedValue(expirationStr);
                }
                expirationSecondTime = Long.parseLong(expirationStr);
            }
        }
        if(null == expirationSecondTime){
            expirationSecondTime = this.getExpireTime();
        }
        return expirationSecondTime;
    }
    /**
     * 获取自动刷新时间
     * @return
     */
    @Override
    public Long getRefreshTime(String[] cacheParams) {
        // 自动刷新时间,默认是0
        Long refreshTime = 0L;
        // 设置自动刷新时间
        if (cacheParams.length > 2) {
            String refreshTimeStr = cacheParams[2];
            if (!StringUtils.isEmpty(refreshTimeStr)) {
                // 支持配置刷新时间使用EL表达式读取配置文件时间
                if (refreshTimeStr.contains(MARK)) {
                    refreshTimeStr = beanFactory.resolveEmbeddedValue(refreshTimeStr);
                }
                refreshTime = Long.parseLong(refreshTimeStr);
            }
        }
        if(null == refreshTime){
            refreshTime = this.getRefreshTime();
        }
        return refreshTime;
    }
    @Override
    public Cache getCache(String name){
        String[] cacheParams = name.split(CustomCacheManager.SEPARATOR);
        String cacheName = cacheParams[0];
        if(StringUtils.isEmpty(cacheName)){
            return null;
        }
        //注解里面的过期时间覆盖默认的过期时间
        long expireTime = getExpireTime(name,cacheParams);
        //注解里面的刷新时间
        long refreshTime = getRefreshTime(cacheParams);
        Object obj =  ReflectionUtils.getFieldValue(getInstance(),SUPER_CACHEMAP);
        if(null != obj && obj instanceof ConcurrentHashMap){
            ConcurrentHashMap<String,Cache> cacheMap = (ConcurrentHashMap<String,Cache>)obj;
            return getCache(name,expireTime,refreshTime,cacheMap);
        }else{
            return super.getCache(name);
        }
    }
    /**
     * @param cacheName
     * @param expireTime
     * @param refreshTime
     * @param cacheMap
     * @return
     */
    public Cache getCache(String cacheName, long expireTime, long refreshTime, ConcurrentHashMap<String,Cache> cacheMap){
        Cache cache = cacheMap.get(cacheName);
        if(null != cache){
            return cache;
        }else {
            synchronized (cacheMap){
                cache = cacheMap.get(cacheName);
                if(null == cache){
                    cache = createConcurrentMapCache(cacheName,expireTime,refreshTime);
                    cacheMap.put(cacheName,cache);
                }
            }
        }
        return cache;
    }
    public CustomMapCache createConcurrentMapCache(String cacheName, long expirationTime, long refreshTime) {
        return new CustomMapCache(cacheName,expirationTime,refreshTime);
    }
}

+ 182 - 0
base/common-cache/src/main/java/com/yihu/base/cache/manager/CustomRedisCacheManager.java

@ -0,0 +1,182 @@
package com.yihu.base.cache.manager;
import com.yihu.base.cache.util.ReflectionUtils;
import com.yihu.base.cache.util.SpringContextUtils;
import com.yihu.base.cache.cache.CustomRedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class CustomRedisCacheManager extends RedisCacheManager implements CustomCacheManager{
    @Value("expire-time")
    private Long expireTime;
    @Value("refresh-time")
    private Long refreshTime;
    @Autowired
    private DefaultListableBeanFactory beanFactory;
    private RedisCacheManager redisCacheManager = null;
    //父类存放缓存的cacheMap字段
    private static final String SUPER_CACHEMAP = "cacheMap";
    private static final String SUPER_DYNAMIC = "dynamic";
    //父类cacheNullValues字段
    private static final String SUPER_CACHENULLVALUES = "cacheNullValues";
     // 父类updateCacheNames方法
    private static final String SUPER_METHOD_UPDATECACHENAMES = "updateCacheNames";
    @Override
    public Long getExpireTime() {
        return expireTime;
    }
    @Override
    public Long getRefreshTime() {
        return refreshTime;
    }
    public CustomRedisCacheManager(RedisOperations redisOperations) {
        super(redisOperations);
    }
    public RedisCacheManager getInstance(){
        if(null == redisCacheManager){
            redisCacheManager = SpringContextUtils.getBean(RedisCacheManager.class);
        }
        return redisCacheManager;
    }
    /**
     * 覆盖父类获取cache方法
     * @param name,name为注解上的value,以#分隔,第一个为缓存的名字,第二个为缓存的过期时间,第三个为缓存的自动刷新时间
     * @return
     */
    @Override
    public Cache getCache(String name){
        String[] cacheParams = name.split(CustomCacheManager.SEPARATOR);
        String cacheName = cacheParams[0];
        if(StringUtils.isEmpty(cacheName)){
            return null;
        }
        //注解里面的过期时间覆盖默认的过期时间,Redis默认有提供过期时间,如果没有传值,就用配置的默认刷新时间
        Long expireTime = getExpireTime(name,cacheParams);
        //注解里面的刷新时间,如果没有传值,就用配置的默认刷新时间
        Long refreshTime = getRefreshTime(cacheParams);
        Object obj =  ReflectionUtils.getFieldValue(getInstance(),SUPER_CACHEMAP);
        if(null != obj && obj instanceof ConcurrentHashMap){
            ConcurrentHashMap<String,Cache> cacheMap = (ConcurrentHashMap<String,Cache>)obj;
            return getCache(name,expireTime,refreshTime,cacheMap);
        }else{
            return super.getCache(name);
        }
    }
    /**
     * @param cacheName
     * @param expireTime
     * @param refreshTime
     * @param cacheMap
     * @return
     */
    public Cache getCache(String cacheName, long expireTime, long refreshTime, ConcurrentHashMap<String,Cache> cacheMap){
        Cache cache = cacheMap.get(cacheName);
        if(null != cache){
            return cache;
        }else {
            synchronized (cacheMap){
                cache = cacheMap.get(cacheName);
                if(null == cache){
                    //没有则创建一个cache,带上过期时间和刷新时间
                    cache = getMissingCache(cacheName,expireTime,refreshTime);
                    if(null != cache){
                        cache = decorateCache(cache);
                        cacheMap.put(cacheName,cache);
                        //反射调用父类updateCacheNams方法,同步更新缓存名称集合
                        Class<?>[] parameterTypes = {String.class};
                        Object[] paramters = {cacheName};
                        ReflectionUtils.invokeMethod(getInstance(),SUPER_METHOD_UPDATECACHENAMES,parameterTypes,paramters);
                    }
                }
            }
        }
        return cache;
    }
    public CustomRedisCache getMissingCache(String cacheName, long expirationSecondTime, long refreshTime) {
        Boolean dynamic = (Boolean) ReflectionUtils.getFieldValue(getInstance(),SUPER_DYNAMIC);
        Boolean cacheNullValues = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_CACHENULLVALUES);
        return dynamic ? new CustomRedisCache(cacheName, (this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null),
                this.getRedisOperations(), expirationSecondTime, refreshTime, cacheNullValues) : null;
    }
    /**
     * 获取过期时间
     * @return
     */
    @Override
    public Long getExpireTime(String cacheName, String[] cacheParams) {
        // 有效时间,初始化获取默认的有效时间
        Long expirationSecondTime = this.computeExpiration(cacheName);
        // 设置key有效时间
        if (cacheParams.length > 1) {
            String expirationStr = cacheParams[1];
            if (!StringUtils.isEmpty(expirationStr)) {
                // 支持配置过期时间使用EL表达式读取配置文件时间
                if (expirationStr.contains(MARK)) {
                    expirationStr = beanFactory.resolveEmbeddedValue(expirationStr);
                }
                expirationSecondTime = Long.parseLong(expirationStr);
            }
        }
        if(null == expirationSecondTime){
            expirationSecondTime = this.getExpireTime();
        }
        return expirationSecondTime;
    }
    /**
     * 获取自动刷新时间
     * @return
     */
    @Override
    public Long getRefreshTime(String[] cacheParams) {
        // 自动刷新时间,默认是0
        Long refreshTime = 0L;
        // 设置自动刷新时间
        if (cacheParams.length > 2) {
            String preloadStr = cacheParams[2];
            if (!StringUtils.isEmpty(preloadStr)) {
                // 支持配置刷新时间使用EL表达式读取配置文件时间
                if (preloadStr.contains(MARK)) {
                    preloadStr = beanFactory.resolveEmbeddedValue(preloadStr);
                }
                refreshTime = Long.parseLong(preloadStr);
            }
        }
        if(null == refreshTime){
            refreshTime = this.getRefreshTime();
        }
        return refreshTime;
    }
}

+ 75 - 0
base/common-cache/src/main/java/com/yihu/base/cache/support/CacheInvocation.java

@ -0,0 +1,75 @@
package com.yihu.base.cache.support;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class CacheInvocation {
    private Object key;
    private Object targetBean;
    private Method targetMethod;
    private Object[] arguments;
    private List<String> parameterTypes = new ArrayList<>();
    public CacheInvocation(Object key,Object targetBean,Method targetMethod,Object[] arguments,Class[] parameterTypes){
        this.key = key;
        this.targetBean = targetBean;
        this.targetMethod = targetMethod;
        if(null != arguments && arguments.length > 0){
            this.arguments = Arrays.copyOf(arguments,arguments.length);
        }
        if(null != parameterTypes && parameterTypes.length > 0){
            for( Class cls:parameterTypes){
                this.parameterTypes.add(cls.getName());
            }
        }
    }
    /**
     * 重写equals方法
     * @param obj
     * @return
     */
    @Override
    public boolean equals(Object obj){
        if(obj == this){
            return true;
        }
        if(null == obj || obj.getClass() != getClass()){
            return false;
        }
        CacheInvocation cacheInvocation = (CacheInvocation)obj;
        return key.equals(cacheInvocation.key);
    }
    /**
     * 重写hashCode方法
     * @return
     */
    @Override
    public int hashCode(){
        return key.hashCode();
    }
    public Object getKey() {
        return key;
    }
    public Object getTargetBean() {
        return targetBean;
    }
    public Method getTargetMethod() {
        return targetMethod;
    }
    public Object[] getArguments() {
        return arguments;
    }
}

+ 33 - 0
base/common-cache/src/main/java/com/yihu/base/cache/support/CacheSupport.java

@ -0,0 +1,33 @@
package com.yihu.base.cache.support;
import java.lang.reflect.Method;
import java.util.Set;
/**
 * 注册和刷新缓存接口
 */
public interface CacheSupport {
    String SPERATOR = "#";
    /**
     * 注册缓存方法信息
     *
     * @param invokedBean          代理Bean
     * @param invokedMethod        代理方法名称
     * @param invocationParamTypes 代理方法参数类型
     * @param invocationArgs       代理方法参数
     * @param annoationCacheNames           缓存名称(@Cacheable注解的value)
     * @param cacheKey             缓存key(@Cacheable注解的key)
     */
    void registerInvocation(Object invokedBean, Method invokedMethod, Class[] invocationParamTypes, Object[] invocationArgs, Set<String> annoationCacheNames, String cacheKey);
    /**
     * 按容器以及指定键更新缓存
     *
     * @param cacheName
     * @param cacheKey
     */
    void refreshCacheByKey(String cacheName, String cacheKey);
}

+ 88 - 0
base/common-cache/src/main/java/com/yihu/base/cache/support/CacheSupportImpl.java

@ -0,0 +1,88 @@
package com.yihu.base.cache.support;
import com.yihu.base.cache.manager.CacheManagerFactory;
import com.yihu.base.cache.manager.CustomCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MethodInvoker;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class CacheSupportImpl implements CacheSupport {
    /**
     * 根据name获取cache列表
     * @param annoationCacheName
     * @return
     */
    public Collection<? extends Cache> getCache(Set<String> annoationCacheName){
        Collection<String> cacheNames = getAnnoationValues(annoationCacheName);
        if(null == cacheNames){
            return Collections.EMPTY_LIST;
        }
        Collection<Cache> cacheResults = new ArrayList<>();
        CacheManagerFactory cacheManagerFactory = new CacheManagerFactory();
        for(String cacheName:cacheNames){
            Cache cache = cacheManagerFactory.getCacheManager().getCache(cacheName);
            if(null == cache){
                throw new IllegalArgumentException("cannot find cache named "+cacheName);
            }
            cacheResults.add(cache);
        }
        return cacheResults;
    }
    /**
     * 获取注解上的cacheName值
     * @param annoationNames
     * @return
     */
    public Collection<String> getAnnoationValues(Set<String> annoationNames){
        Collection<String> cacheNames = new HashSet<>();
        for(String cacheName:annoationNames){
            String[] cacheParams =  cacheName.split(CacheSupport.SPERATOR);
            //注解的“#”前的第一个为缓存的name
            String realCacheName = cacheParams[0];
            cacheNames.add(realCacheName);
        }
        return  cacheNames;
    }
    /**
     * 调用方法
     * @param cacheInvocation
     * @return
     */
    public Object invoke(CacheInvocation cacheInvocation){
        Object object = null;
        MethodInvoker methodInvoker =  new MethodInvoker();
        methodInvoker.setTargetObject(cacheInvocation.getTargetBean());
        methodInvoker.setTargetMethod(cacheInvocation.getTargetMethod().getName());
        methodInvoker.setArguments(cacheInvocation.getArguments());
        try {
            methodInvoker.prepare();
            object = methodInvoker.invoke();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
    @Override
    public void registerInvocation(Object invokedBean, Method invokedMethod, Class[] invocationParamTypes, Object[] invocationArgs, Set<String> annoationCacheNames, String cacheKey) {
    }
    @Override
    public void refreshCacheByKey(String cacheName, String cacheKey) {
    }
}

+ 83 - 0
base/common-cache/src/main/java/com/yihu/base/cache/support/CachingAnnoationAspect.java

@ -0,0 +1,83 @@
package com.yihu.base.cache.support;
import com.yihu.base.cache.support.CacheSupport;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.*;
@Aspect
@Component
public class CachingAnnoationAspect {
    @Autowired
    private CacheSupport cacheSupport;
    private <T extends Annotation> List<T> getMethodAnnotations(AnnotatedElement annotatedElement,Class<T> annotationType){
        List<T> anns = new ArrayList<T>();
        T ann = annotatedElement.getAnnotation(annotationType);
        if (null != ann) {
            anns.add(ann);
        }
        for(Annotation annotation:annotatedElement.getAnnotations()){
            ann = annotation.annotationType().getAnnotation(annotationType);
            if(null != ann){
                anns.add(ann);
            }
        }
        return anns.isEmpty() ? null : anns;
    }
    private Method getSpecificMethod(ProceedingJoinPoint proceedingJoinPoint){
        MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Class<?> targetClass = AopProxyUtils.ultimateTargetClass(proceedingJoinPoint.getTarget());
        if(null == targetClass && null != proceedingJoinPoint.getTarget()){
            targetClass = proceedingJoinPoint.getTarget().getClass();
        }
        Method specificMethod = ClassUtils.getMostSpecificMethod(method,targetClass);
        specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        return specificMethod;
    }
    @Pointcut("@annotation(org.springframework.cache.annotation.Cacheable)")
    public void pointcut(){}
    @Around("pointcut()")
    public Object registerInvocation(ProceedingJoinPoint proceedingJoinPoint){
        Object object = null;
        Method method = getSpecificMethod(proceedingJoinPoint);
        List<Cacheable> annotations =  getMethodAnnotations(method,Cacheable.class);
        Set<String> cacheSet = new HashSet<>();
        String cacheKey = "";
        for (Cacheable cacheables:annotations) {
             cacheSet.addAll(Arrays.asList(cacheables.value()));
             cacheKey = cacheables.key();
        }
        if(proceedingJoinPoint.getSignature() instanceof MethodSignature){
            Class[] parameterTpyes = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterTypes();
            cacheSupport.registerInvocation(proceedingJoinPoint.getTarget(),method,parameterTpyes,proceedingJoinPoint.getArgs(),cacheSet,cacheKey);
        }
        try {
            object = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return object;
    }
}

+ 64 - 0
base/common-cache/src/main/java/com/yihu/base/cache/support/MapCacheSupportImpl.java

@ -0,0 +1,64 @@
package com.yihu.base.cache.support;
import com.yihu.base.cache.cache.CustomMapCache;
import com.yihu.base.cache.config.CacheKeyGenerator;
import com.yihu.base.cache.manager.CustomCacheManager;
import com.yihu.base.cache.util.ReflectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Component
public class MapCacheSupportImpl extends CacheSupportImpl implements CacheSupport {
    private ConcurrentMap<String,Object> invocationMap = new ConcurrentHashMap<>();
    @Autowired
    private CustomCacheManager customCacheManager;
    @Override
    public void registerInvocation(Object invokedBean, Method invokedMethod, Class[] invocationParamTypes, Object[] invocationArgs, Set<String> annoationCacheNames, String cacheKey) {
        Collection<? extends Cache> caches = getCache(annoationCacheNames);
        CacheInvocation cacheInvocation = new CacheInvocation(CacheKeyGenerator.getCacheKey(),invokedBean,invokedMethod,invocationArgs,invocationParamTypes);
        for(Cache cache:caches){
            if(cache instanceof CustomMapCache){
                CustomMapCache customMapCache = (CustomMapCache)cache;
                Long diffTime = System.currentTimeMillis() - customMapCache.getStartTime();
                if(diffTime >= customMapCache.getExpireTime() || diffTime <= customMapCache.getRefreshTime()){
                    invocationMap.put(cacheKey,cacheInvocation);
                }
            }
        }
    }
    @Override
    public void refreshCacheByKey(String cacheName, String cacheKey) {
        CacheInvocation cacheInvocation = (CacheInvocation)invocationMap.get(cacheKey);
        if(null != cacheInvocation){
            refreshCache(cacheInvocation,cacheName);
        }
    }
    private void refreshCache(CacheInvocation cacheInvocation,String cacheName){
        Object computed = invoke(cacheInvocation);
        //获取缓存对象
//        ConcurrentMapCacheManager concurrentMapCacheManager = new ConcurrentMapCacheManager();
        Cache cache = customCacheManager.getCache(cacheName);
        //更新缓存
        cache.put(cacheInvocation.getKey(),computed);
        CustomMapCache customMapCache = (CustomMapCache)cache;
        invocationMap.remove(customMapCache.getName());
        ConcurrentMap<Object, Object> cacheMap = (ConcurrentMap<Object, Object>) ReflectionUtils.getFieldValue(ConcurrentMapCache.class, "store");
        cacheMap.remove(customMapCache.getName());
    }
}

+ 60 - 0
base/common-cache/src/main/java/com/yihu/base/cache/support/RedisCacheSupportImpl.java

@ -0,0 +1,60 @@
package com.yihu.base.cache.support;
import com.yihu.base.cache.cache.CustomRedisCache;
import com.yihu.base.cache.config.CacheKeyGenerator;
import com.yihu.base.cache.manager.CustomCacheManager;
import com.yihu.base.cache.util.RedisTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisCacheSupportImpl extends CacheSupportImpl implements CacheSupport {
    @Autowired
    private CustomCacheManager customCacheManager;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Override
    public void registerInvocation(Object invokedBean, Method invokedMethod, Class[] invocationParamTypes, Object[] invocationArgs, Set<String> annoationCacheNames, String cacheKey) {
        Collection<? extends Cache> caches = getCache(annoationCacheNames);
        CacheInvocation cacheInvocation = new CacheInvocation(CacheKeyGenerator.getCacheKey(),invokedBean,invokedMethod,invocationArgs,invocationParamTypes);
        for(Cache cache:caches){
            if(cache instanceof CustomRedisCache){
                CustomRedisCache customRedisCache = (CustomRedisCache)cache;
                RedisTemplate redisTemplate = RedisTemplateUtils.getRedisTemplate(redisConnectionFactory);
                redisTemplate.opsForValue().set(CacheKeyGenerator.getCacheKey(),cacheInvocation,customRedisCache.getExpireTime(), TimeUnit.SECONDS);
            }
        }
    }
    @Override
    public void refreshCacheByKey(String cacheName, String cacheKey) {
        RedisTemplate redisTemplate = RedisTemplateUtils.getRedisTemplate(redisConnectionFactory);
        CacheInvocation cacheInvocation = (CacheInvocation)redisTemplate.opsForValue().get(cacheKey);
        if(null != cacheInvocation){
            refreshCache(cacheName,cacheInvocation);
        }
    }
    public void refreshCache(String cacheName,CacheInvocation cacheInvocation){
        Object computed = invoke(cacheInvocation);
        //获取缓存对象
        Cache cache = customCacheManager.getCache(cacheName);
        //更新缓存
        cache.put(cacheInvocation.getKey(),computed);
        RedisTemplate redisTemplate = RedisTemplateUtils.getRedisTemplate(redisConnectionFactory);
        CustomRedisCache customRedisCache = (CustomRedisCache)cache;
        redisTemplate.expire(cacheInvocation.getKey(),customRedisCache.getExpireTime(),TimeUnit.SECONDS);
    }
}

+ 34 - 0
base/common-cache/src/main/java/com/yihu/base/cache/util/RedisTemplateUtils.java

@ -0,0 +1,34 @@
package com.yihu.base.cache.util;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
public class RedisTemplateUtils {
    private static RedisTemplate redisTemplate;
    public static RedisTemplate getRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        if(null == redisTemplate){
            synchronized (RedisTemplateUtils.class){
                if(null == redisTemplate){
                    redisTemplate = new RedisTemplate();
                    redisTemplate.setConnectionFactory(redisConnectionFactory);
                    JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
                    redisTemplate.setValueSerializer(jdkSerializationRedisSerializer);
                    redisTemplate.setHashValueSerializer(jdkSerializationRedisSerializer);
                    //key采用StringRedisSserializer来序列化
                    redisTemplate.setKeySerializer(new StringRedisSerializer());
                    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
                    redisTemplate.afterPropertiesSet();
                }
            }
        }
        return redisTemplate;
    }
}

+ 145 - 0
base/common-cache/src/main/java/com/yihu/base/cache/util/ReflectionUtils.java

@ -0,0 +1,145 @@
package com.yihu.base.cache.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionUtils {
    /**
     * 循环向上转型, 获取对象的 DeclaredMethod
     * @param object : 子类对象
     * @param methodName : 父类中的方法名
     * @param parameterTypes : 父类中的方法参数类型
     * @return 父类中的方法对象
     */
    public static Method getDeclaredMethod(Object object, String methodName, Class<?> ... parameterTypes){
        Method method = null ;
        for(Class<?> clazz = object.getClass() ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, parameterTypes) ;
                return method ;
            } catch (Exception e) {
                //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
                //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }
        return null;
    }
    /**
     * 直接调用对象方法, 而忽略修饰符(private, protected, default)
     * @param object : 子类对象
     * @param methodName : 父类中的方法名
     * @param parameterTypes : 父类中的方法参数类型
     * @param parameters : 父类中的方法参数
     * @return 父类中方法的执行结果
     */
    public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
                                      Object [] parameters) {
        //根据 对象、方法名和对应的方法参数 通过反射 调用上面的方法获取 Method 对象
        Method method = getDeclaredMethod(object, methodName, parameterTypes) ;
        //抑制Java对方法进行检查,主要是针对私有方法而言
        method.setAccessible(true) ;
        try {
            if(null != method) {
                //调用object 的 method 所代表的方法,其方法的参数是 parameters
                return method.invoke(object, parameters) ;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 循环向上转型, 获取对象的 DeclaredField
     * @param object : 子类对象
     * @param fieldName : 父类中的属性名
     * @return 父类中的属性对象
     */
    public static Field getDeclaredField(Object object, String fieldName){
        Field field = null ;
        Class<?> clazz = object.getClass() ;
        for(; clazz != Object.class ; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName) ;
                return field ;
            } catch (Exception e) {
                //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
                //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }
        return null;
    }
    /**
     * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
     * @param object : 子类对象
     * @param fieldName : 父类中的属性名
     * @param value : 将要设置的值
     */
    public static void setFieldValue(Object object, String fieldName, Object value){
        //根据 对象和属性名通过反射 调用上面的方法获取 Field对象
        Field field = getDeclaredField(object, fieldName) ;
        //抑制Java对其的检查
        field.setAccessible(true) ;
        try {
            //将 object 中 field 所代表的值 设置为 value
            field.set(object, value) ;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    /**
     * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
     * @param object : 子类对象
     * @param fieldName : 父类中的属性名
     * @return : 父类中的属性值
     */
    public static Object getFieldValue(Object object, String fieldName){
        //根据 对象和属性名通过反射 调用上面的方法获取 Field对象
        Field field = getDeclaredField(object, fieldName) ;
        //抑制Java对其的检查
        field.setAccessible(true) ;
        try {
            //获取 object 中 field 所代表的属性值
            return field.get(object) ;
        } catch(Exception e) {
            e.printStackTrace() ;
        }
        return null;
    }
}

+ 68 - 0
base/common-cache/src/main/java/com/yihu/base/cache/util/SpringContextUtils.java

@ -0,0 +1,68 @@
package com.yihu.base.cache.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * Spring上下文管理器
 * @author LiTaohong
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext springContext = null;
    /**
     * 获取Spring应用上下文环境
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return springContext;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        springContext = applicationContext;
    }
    /**
     * 获取Bean
     *
     * @param serviceName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String serviceName) {
        return (T) springContext.getBean(serviceName);
    }
    public static <T> T getBean(Class<T> beanCls) {
        return (T) springContext.getBean(beanCls);
    }
    /**
     * 获取服务,并用参数初始化对象。
     *
     * @param serviceName
     * @param args
     * @param <T>
     * @return
     */
    public static <T> T getBean(String serviceName, Object... args) {
        T ref = (T)springContext.getBean(serviceName, args);
        if (ref == null) return null;
        return ref;
    }
    public static <T> T getBean(Class<T> beanCls, Object... args){
        T ref = (T)springContext.getBean(beanCls, args);
        if (ref == null) return null;
        return ref;
    }
}

+ 32 - 0
base/common-cache/src/main/java/com/yihu/base/cache/util/ThreadTaskUtils.java

@ -0,0 +1,32 @@
package com.yihu.base.cache.util;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
 *
 */
public class ThreadTaskUtils {
    private static ThreadPoolTaskExecutor taskExecutor = null;
    static {
        taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(5);
        // 最大线程数
        taskExecutor.setMaxPoolSize(50);
        // 队列最大长度
        taskExecutor.setQueueCapacity(1000);
        // 线程池维护线程所允许的空闲时间(单位秒)
        taskExecutor.setKeepAliveSeconds(120);
        // 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        taskExecutor.initialize();
    }
    public static void run(Runnable runnable) {
        taskExecutor.execute(runnable);
    }
}

+ 17 - 0
base/common-cache/src/main/resources/template.yml

@ -0,0 +1,17 @@
cache: 1 # 1-内存 2-redis
spring:
  redis:
    host: 172.19.103.88 # ip
    port: 6379 # R端口
    database: 0 # 默认使用DB0
    timeout: 0 # 连接超时时间(毫秒)
      #sentinel:
      #  master: # Name of Redis server.
      #  nodes: # Comma-separated list of host:port pairs.
    pool: ##连接池配置
      max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
      max-idle: 8 # 连接池中的最大空闲连接
      max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
      min-idle: 1 # 连接池中的最小空闲连接

+ 5 - 5
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseUserRequestMapping.java

@ -28,7 +28,7 @@ public class BaseUserRequestMapping {
        public static final String message_fail_saasid_no_exist = "saasId no exist";
        public static final String message_fail_role_no_exist = "baseRole no exist";
        public static final String message_param_id_is_null = "baseRole id param cannot be null";
        public static final String message_fail_params_not_present = "baseRole id param cannot be null";
        public static final String message_param_saasid_is_null = "baseRole saasId param cannot be null";
        public static final String message_param_name_is_null = "baseRole name param cannot be null";
    }
@ -41,10 +41,10 @@ public class BaseUserRequestMapping {
        public static final String api_update = "/employee";
        public static final String api_delete = "/employee/{ids}";
        public static final String api_getById = "/employee/{id}";
        public static final String api_getByUserId = "/employeeById/{userId}";
        public static final String api_getByPhone = "/employee";
        public static final String api_getList="/employee/list";
        public static final String api_getListNoPage="/employee/listNoPage";
        public static final String api_getByEmployId = "/employee/{employId}";
        public static final String api_getRolesByEmployId = "/employee/{employId}";
        public static final String message_success_create="Employee create success";
@ -52,12 +52,12 @@ public class BaseUserRequestMapping {
        public static final String message_success_delete="Employee delete success";
        public static final String message_success_find="Employee find success";
        public static final String message_fail_name_exist = "baseRole name exist";
        public static final String message_fail_params_not_present = "employee all params must be present ";
        public static final String message_fail_name_is_null = "baseRole is null";
        public static final String message_fail_id_is_null = "id is null";
        public static final String message_fail_id_no_exist = "id no exist";
        public static final String message_fail_saasid_is_null = "saasId is null";
        public static final String message_param_saasid_is_null = "baseRole saasId param cannot be null";
        public static final String message_param_saasid_is_null = "employee saasId param cannot be null";
        public static final String message_fail_saasid_no_exist = "saasId no exist";
    }

+ 175 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/user/BaseEmployVO.java

@ -0,0 +1,175 @@
package com.yihu.jw.restmodel.base.user;
public class BaseEmployVO {
    private String id; //id
    private String saasId; //saasIDF
    private String name; //名字
    private String pyCode; //拼音
    private String sex; //性别
    private String photo; //头像
    private String skill;//专长
    private String workPortal;//医生门户首页
    private String email;//邮箱
    private String phone;//联系电话
    private String secondPhone;//备用电话
    private String familyTel;//家庭电话(固)
    private String officeTel;//办公电话(固)
    private String introduction;//简介
    private String jxzc;//教学职称
    private String lczc;//临床职称
    private String xlzc;//学历职称
    private String xzzc;//行政职称
    private Integer status;//-1 删除 0 禁用 1可用
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPyCode() {
        return pyCode;
    }
    public void setPyCode(String pyCode) {
        this.pyCode = pyCode;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    public String getSkill() {
        return skill;
    }
    public void setSkill(String skill) {
        this.skill = skill;
    }
    public String getWorkPortal() {
        return workPortal;
    }
    public void setWorkPortal(String workPortal) {
        this.workPortal = workPortal;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getSecondPhone() {
        return secondPhone;
    }
    public void setSecondPhone(String secondPhone) {
        this.secondPhone = secondPhone;
    }
    public String getFamilyTel() {
        return familyTel;
    }
    public void setFamilyTel(String familyTel) {
        this.familyTel = familyTel;
    }
    public String getOfficeTel() {
        return officeTel;
    }
    public void setOfficeTel(String officeTel) {
        this.officeTel = officeTel;
    }
    public String getIntroduction() {
        return introduction;
    }
    public void setIntroduction(String introduction) {
        this.introduction = introduction;
    }
    public String getJxzc() {
        return jxzc;
    }
    public void setJxzc(String jxzc) {
        this.jxzc = jxzc;
    }
    public String getLczc() {
        return lczc;
    }
    public void setLczc(String lczc) {
        this.lczc = lczc;
    }
    public String getXlzc() {
        return xlzc;
    }
    public void setXlzc(String xlzc) {
        this.xlzc = xlzc;
    }
    public String getXzzc() {
        return xzzc;
    }
    public void setXzzc(String xzzc) {
        this.xzzc = xzzc;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 85 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/user/BaseMenuVO.java

@ -0,0 +1,85 @@
package com.yihu.jw.restmodel.base.user;
public class BaseMenuVO {
    private String id;
    private String url;//请求路径
    private String method;//请求方式 get post
    private String saasId;
    private String parentId;
    private String name;
    private Integer sort;
    private Integer status;
    private String remark;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getParentId() {
        return parentId;
    }
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
}

+ 50 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/user/BaseRoleVO.java

@ -0,0 +1,50 @@
package com.yihu.jw.restmodel.base.user;
public class BaseRoleVO {
    private String id;
    private String saasId;
    private String name;
    private Integer status;
    private String remark;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
}

+ 5 - 0
svr/svr-base/pom.xml

@ -132,6 +132,11 @@
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>common-customCache</groupId>
            <artifactId>common-customCache</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-base</finalName>

+ 117 - 3
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseRoleController.java

@ -1,29 +1,46 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.base.user.BaseRoleMenuDO;
import com.yihu.jw.business.user.service.BaseRoleMenuService;
import com.yihu.jw.business.user.service.BaseRoleService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.restmodel.base.user.BaseEmployVO;
import com.yihu.jw.restmodel.base.user.BaseRoleVO;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@RestController
@RequestMapping("/role")
@Api(description = "角色")
@Api(description = "基础角色")
public class BaseRoleController extends EnvelopRestController {
    @Autowired
    private BaseRoleService baseRoleService;
    @Autowired
    private BaseRoleMenuService baseRoleMenuService;
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建角色", notes = "创建单个角色")
    public Envelop createRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
@ -69,16 +86,47 @@ public class BaseRoleController extends EnvelopRestController {
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_getList, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询多个角色", notes = "根据平台id查询所有角色信息")
    @ApiOperation(value = "查询多个角色", notes = "根据平台id查询所有角色信息,不分页")
    public Envelop getRoleListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findAllBySaasId(baseRoleDO.getSaasId()));
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findAllBySaasId(baseRoleDO.getSaasId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据指定条件查询所有角色列表,分页")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getRoleListPage(@ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,remark") @RequestParam(value = "fields", required = false) String fields,
                                              @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                                              @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime") @RequestParam(value = "sorts", required = false) String sorts,
                                              @ApiParam(name = "size", value = "分页大小", defaultValue = "15") @RequestParam(value = "size", required = false) int size,
                                              @ApiParam(name = "page", value = "页码", defaultValue = "1") @RequestParam(value = "page", required = false) int page,
                                              HttpServletRequest request, HttpServletResponse response) throws ParseException {
        if (StringUtils.isBlank(filters)) {
            return Envelop.getError(BaseUserRequestMapping.BaseRole.message_fail_params_not_present, ExceptionCode.common_error_params_code);
        } else {
            filters = "status<>-1;" + filters;
        }
        if (StringUtils.isBlank(sorts)) {
            sorts = "-updateTime";
        }
        //得到list数据
        List<BaseRoleVO> list = baseRoleService.search(fields, filters, sorts, page, size);
        //获取总数
        long count = baseRoleService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<BaseRoleVO> mFunctions = convertToModels(list, new ArrayList<>(list.size()), BaseRoleVO.class, fields);
        return Envelop.getSuccessListWithPage(BaseUserRequestMapping.BaseRole.message_success_find, mFunctions, page, size, count);
    }
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除角色", notes = "根据角色id删除角色")
    public Envelop deleteRole(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
@ -103,4 +151,70 @@ public class BaseRoleController extends EnvelopRestController {
        }
    }
    @ApiOperation(value = "給角色添加菜单", notes = "給角色添加菜单")
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop addMenuForRole(@ApiParam(name = "roleId", value = "", defaultValue = "") @RequestBody String roleId,
                                  @ApiParam(name = "menuIds", value = "", defaultValue = "") @RequestBody String menuIds){
        try{
            String[] menuIdArray = menuIds.split(",");
            List<BaseRoleMenuDO> list = new ArrayList<>();
            for(String menuId:menuIdArray){
                BaseRoleMenuDO baseRoleMenuDO = new BaseRoleMenuDO();
                baseRoleMenuDO.setRoleId(roleId);
                baseRoleMenuDO.setRoleId(menuId);
            }
            if(menuIdArray.length < 1){
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,this.baseRoleMenuService.createBaseRoleMenuDO(list.get(0)));
            }else{
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,this.baseRoleMenuService.createBatchBaseRoleMenuDO(list));
            }
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "修改角色菜单")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_update)
    public Envelop updateMenuForRole(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String id,
                                    @ApiParam(name = "newMenuId", value = "newMenuId", required = true) @RequestParam(value = "roleId", required = true) String newMenuId) {
        try {
            BaseRoleMenuDO baseEmployRoleDO = new BaseRoleMenuDO();
            baseEmployRoleDO.setId(id);
            baseEmployRoleDO.setMenuId(newMenuId);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.baseRoleMenuService.updateBaseEmployRoleDO(baseEmployRoleDO));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "查看角色菜单列表,不分页")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getRolesByEmployId)
    public Envelop findMenuListForRole(@ApiParam(name = "roleId", value = "roleId", required = true) @RequestParam(value = "roleId", required = true) String roleId) {
        try {
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.baseRoleMenuService.findAllByRoleId(roleId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "删除角色菜单", notes = "删除角色菜单")
    @PostMapping(value = BaseUserRequestMapping.BaseRole.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop deleteMenuForRole(@ApiParam(name = "roleId", value = "", defaultValue = "") @RequestBody String roleId,
                                  @ApiParam(name = "menuIds", value = "", defaultValue = "") @RequestBody String menuIds){
        try{
            String[] menuIdArray = menuIds.split(",");
            if(menuIdArray.length < 1){
                this.baseRoleMenuService.deleteBaseRoleMenuDO(roleId,menuIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete,"删除角色单个菜单信息");
            }else{
                this.baseRoleMenuService.deleteBatchBaseRoleMenuDO(roleId,menuIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete,"删除角色多个菜单信息");
            }
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}

+ 129 - 9
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployController.java

@ -1,21 +1,32 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.base.FunctionDO;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.business.user.service.EmployRoleService;
import com.yihu.jw.business.user.service.EmployService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.restmodel.base.base.FunctionVO;
import com.yihu.jw.restmodel.base.user.BaseEmployVO;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 */
@ -26,13 +37,15 @@ public class EmployController extends EnvelopRestController {
    @Autowired
    private EmployService employService;
    @Autowired
    private EmployRoleService employRoleService;
    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建用户", notes = "创建单个用户")
    public Envelop createBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_create,employService.createBaseEmployDO(baseEmployDO));
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_create,employService.createBaseEmployDO(baseEmployDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
@ -43,17 +56,17 @@ public class EmployController extends EnvelopRestController {
    public Envelop updateBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_update,employService.updateBaseEmployDO(baseEmployDO));
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_update,employService.updateBaseEmployDO(baseEmployDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据id查找用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getById)
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getByPhone)
    public Envelop getEmployeeById(@ApiParam(name = "id", value = "id", required = true) @RequestParam(value = "id", required = true) String id) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,this.employService.findById(id));
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findById(id));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
@ -63,21 +76,128 @@ public class EmployController extends EnvelopRestController {
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getAllEmployeeBySaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,this.employService.findAllBySaasId(saasId));
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findAllBySaasId(saasId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据手机号和saasId查找用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getEmployeeByPhoneAndSaasId(@ApiParam(name = "phone", value = "phone", required = true) @RequestParam(value = "phone", required = true) String phone,
                                               @ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
        try {
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employService.findByPhoneAndSaasId(phone,saasId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据name模糊查询某saasId平台下的所有用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getListByNameAndSaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
    public Envelop getListByNameAndSaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId,
                                          @ApiParam(name = "name", value = "name", required = true) @RequestParam(value = "name", required = true) String name) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,this.employService.findAllBySaasId(saasId));
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_find,this.employService.findAllByNameAndSaasId(name,saasId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据指定条件查询用户列表,分页")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getListPageByNameAndSaasId(@ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,sex,photo,skill,email,phone,family_tel,introduction,jxzc,lczc,xlzc,xzzc") @RequestParam(value = "fields", required = false) String fields,
                                              @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                                              @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime") @RequestParam(value = "sorts", required = false) String sorts,
                                              @ApiParam(name = "size", value = "分页大小", defaultValue = "15") @RequestParam(value = "size", required = false) int size,
                                              @ApiParam(name = "page", value = "页码", defaultValue = "1") @RequestParam(value = "page", required = false) int page,
                                              HttpServletRequest request, HttpServletResponse response) throws ParseException {
        if (StringUtils.isBlank(filters)) {
            return Envelop.getError(BaseUserRequestMapping.BaseEmploy.message_fail_params_not_present, ExceptionCode.common_error_params_code);
        } else {
            filters = "status<>-1;" + filters;
        }
        if (StringUtils.isBlank(sorts)) {
            sorts = "-updateTime";
        }
        //得到list数据
        List<BaseEmployVO> list = employService.search(fields, filters, sorts, page, size);
        //获取总数
        long count = employService.getCount(filters);
        //封装头信息
        pagedResponse(request, response, count, page, size);
        //封装返回格式
        List<BaseEmployVO> mFunctions = convertToModels(list, new ArrayList<>(list.size()), BaseEmployVO.class, fields);
        return Envelop.getSuccessListWithPage(BaseUserRequestMapping.BaseEmploy.message_success_find, mFunctions, page, size, count);
    }
    @ApiOperation(value = "给某一用户新增角色")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_create)
    public Envelop createEmployRoles(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId,
                                     @ApiParam(name = "roleIds", value = "roleIds", required = true) @RequestParam(value = "roleIds", required = true) String roleIds) {
        try {
            String[] roleIdArray = roleIds.split(",");
            List<BaseEmployRoleDO> list = new ArrayList<>();
            for (String roleId : roleIdArray) {
                BaseEmployRoleDO baseEmployRoleDO = new BaseEmployRoleDO();
                baseEmployRoleDO.setEmployId(employId);
                baseEmployRoleDO.setRoleId(roleId);
                list.add(baseEmployRoleDO);
            }
            if (roleIdArray.length < 1) {
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employRoleService.createBaseEmployRoleDO(list.get(0)));
            }else{
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_find, this.employRoleService.createBatchBaseEmployRoleDO(list));
            }
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "修改用户角色")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_update)
    public Envelop updateEmployRole(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String id,
                                    @ApiParam(name = "roleId", value = "roleId", required = true) @RequestParam(value = "roleId", required = true) String newRoleId) {
        try {
            BaseEmployRoleDO baseEmployRoleDO = new BaseEmployRoleDO();
            baseEmployRoleDO.setId(id);
            baseEmployRoleDO.setRoleId(newRoleId);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.employRoleService.updateBaseEmployRoleDO(baseEmployRoleDO));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "查看用户角色列表,不分页")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getRolesByEmployId)
    public Envelop findEmployRoleList(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId) {
        try {
            return Envelop.getSuccessList(BaseUserRequestMapping.BaseEmploy.message_success_delete, this.employRoleService.findAllByEmployId(employId));
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "删除用户角色")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_delete)
    public Envelop deleteEmployRoles(@ApiParam(name = "employId", value = "employId", required = true) @RequestParam(value = "employId", required = true) String employId,
                                     @ApiParam(name = "roleIds", value = "roleIds", required = true) @RequestParam(value = "roleIds", required = true) String roleIds) {
        try {
            String[] idArray = roleIds.split(",");
            if (idArray.length < 1) {
                this.employRoleService.deleteBaseEmployRoleDO(employId,roleIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete,"删除单个角色");
            }else{
                this.employRoleService.deleteBatchBaseEmployRoleDO(employId,roleIds);
                return Envelop.getSuccess(BaseUserRequestMapping.BaseEmploy.message_success_delete, "删除多个角色");
            }
        } catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}

+ 6 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleMenuDao.java

@ -17,4 +17,10 @@ public interface BaseRoleMenuDao extends PagingAndSortingRepository<BaseRoleMenu
    @Query("from BaseRoleMenuDO ba where ba.roleId = ?1")
    List<BaseRoleMenuDO> findRoleMenuListByRoleId(String employId);
    @Query("delete from BaseRoleMenuDO ba where ba.roleId = ?1 and ba.menuId = ?2")
    int deleteOneByRoleIdAndMenuId(String roleId,String menuId);
    @Query("delete from BaseRoleMenuDO ba where ba.roleId = ?1 and ba.menuId in (?2)")
    int deleteManyByRoleIdAndMenuIds(String roleId,String menuIds);
}

+ 3 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployDao.java

@ -21,4 +21,7 @@ public interface EmployDao extends PagingAndSortingRepository<BaseEmployDO, Stri
    @Query("from BaseEmployDO ba where ba.name like ?1 and ba.saasId = ?2")
    List<BaseEmployDO> findAllByNameAndSaasId(String name,String saasId);
    @Query("from BaseEmployDO ba where ba.phone = ?1 and ba.saasId = ?2")
    BaseEmployDO findByPhoneAndSaasId(String phone,String saasId);
}

+ 6 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployRoleDao.java

@ -15,4 +15,10 @@ public interface EmployRoleDao extends PagingAndSortingRepository<BaseEmployRole
    @Query("from BaseEmployRoleDO ba where ba.employId = ?1")
    List<BaseEmployRoleDO> findRoleListByEmployId(String employId);
    @Query("delete from BaseEmployRoleDO ba where ba.employId = ?1 and ba.roleId = ?2")
    int deleteOneByEmployIdAndRoleId(String employId,String roleId);
    @Query("delete from BaseEmployRoleDO ba where ba.employId = ?1 and ba.roleId in (?2)")
    int deleteManyByEmployIdAndRoleIds(String employId,String roleIds);
}

+ 63 - 9
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleMenuService.java

@ -1,7 +1,9 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseRoleMenuDO;
import com.yihu.jw.business.user.dao.BaseMenuDao;
import com.yihu.jw.business.user.dao.BaseRoleMenuDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
@ -11,6 +13,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
@ -23,17 +26,20 @@ public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleM
    @Autowired
    private BaseRoleMenuDao baseRoleMenuDao;
    @Autowired
    private BaseMenuDao baseMenuDao;
    /**
     * 新增角色菜单
     * @param baseEmployRoleDO
     * @param baseRoleMenuDO
     * @return
     */
    @Transactional
    public BaseRoleMenuDO createBaseEmployRoleDO(BaseRoleMenuDO baseEmployRoleDO){
        if (StringUtils.isEmpty(baseEmployRoleDO.getRoleId())) {
    public BaseRoleMenuDO createBaseRoleMenuDO(BaseRoleMenuDO baseRoleMenuDO){
        if (StringUtils.isEmpty(baseRoleMenuDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseRoleMenuDao.save(baseEmployRoleDO);
        return this.baseRoleMenuDao.save(baseRoleMenuDO);
    }
    /**
@ -42,8 +48,8 @@ public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleM
     * @return
     */
    @Transactional
    public void createBatchBaseRoleMenuDO(List<BaseRoleMenuDO> list){
        this.baseRoleMenuDao.save(list);
    public Iterable<BaseRoleMenuDO> createBatchBaseRoleMenuDO(List<BaseRoleMenuDO> list){
        return this.baseRoleMenuDao.save(list);
    }
    /**
@ -61,6 +67,7 @@ public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleM
        if (baseRoleMenuDO.getMenuId().equals(OldbaseRoleMenuDO.getMenuId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_same_menuId, ExceptionCode.common_error_params_code);
        }
        baseRoleMenuDO.setRoleId(OldbaseRoleMenuDO.getRoleId());
        return this.baseRoleMenuDao.save(baseRoleMenuDO);
    }
@ -70,7 +77,7 @@ public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleM
     * @param roleId
     * @return
     */
    public List<BaseRoleMenuDO> findAllByRoleId(String roleId){
    public List<BaseMenuDO> findAllByRoleId(String roleId){
        if (StringUtils.isEmpty(roleId)) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
@ -78,12 +85,18 @@ public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleM
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
        List<String> ids = new ArrayList<>();
        for(BaseRoleMenuDO baseRoleMenuDO:list){
            ids.add(baseRoleMenuDO.getMenuId());
        }
        Iterable<String> iterable = (Iterable<String>)ids.iterator();
        List<BaseMenuDO> result = (List<BaseMenuDO>)baseMenuDao.findAll(iterable);
        return result;
    }
    /**
     * 删除用户角色
     * 根据id删除角色菜单
     * @param id
     * @return
     */
@ -97,4 +110,45 @@ public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleM
        }
    }
    /**
     * 根据roleId和menuId删除角色菜单
     * @param roleId
     * @param menuId
     * @return
     */
    @Transactional
    public void deleteBaseRoleMenuDO(String roleId,String menuId){
        try{
            this.baseRoleMenuDao.deleteOneByRoleIdAndMenuId(roleId,menuId);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
    /**
     * 根据roleId和menuId删除角色菜单
     * @param roleId
     * @param menuIds
     * @return
     */
    @Transactional
    public void deleteBatchBaseRoleMenuDO(String roleId,String menuIds){
        try{
            this.baseRoleMenuDao.deleteManyByRoleIdAndMenuIds(roleId,menuIds);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
}

+ 53 - 5
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployRoleService.java

@ -3,6 +3,8 @@ package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.dao.BaseRoleDao;
import com.yihu.jw.business.user.dao.EmployRoleDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
@ -13,6 +15,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
@ -25,6 +28,9 @@ public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRol
    @Autowired
    private EmployRoleDao employRoleDao;
    @Autowired
    private BaseRoleDao baseRoleDao;
    /**
     * 新增用户角色
     * @param baseEmployRoleDO
@ -47,8 +53,8 @@ public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRol
     * @return
     */
    @Transactional
    public void createBatchBaseEmployRoleDO(List<BaseEmployRoleDO> list){
        this.employRoleDao.save(list);
    public Iterable<BaseEmployRoleDO> createBatchBaseEmployRoleDO(List<BaseEmployRoleDO> list){
       return this.employRoleDao.save(list);
    }
    /**
@ -65,6 +71,7 @@ public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRol
        if (baseEmployRoleDO.getRoleId().equals(OldbaseEmployRoleDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_same_roleId, ExceptionCode.common_error_params_code);
        }
        baseEmployRoleDO.setEmployId(OldbaseEmployRoleDO.getEmployId());
        return this.employRoleDao.save(baseEmployRoleDO);
    }
@ -74,7 +81,7 @@ public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRol
     * @param employId
     * @return
     */
    public List<BaseEmployRoleDO> findAllByEmployId(String employId){
    public List<BaseRoleDO> findAllByEmployId(String employId){
        if (StringUtils.isEmpty(employId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
        }
@ -82,12 +89,18 @@ public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRol
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
        List ids = new ArrayList<>();
        for(BaseEmployRoleDO baseEmployRoleDO:list){
            ids.add(baseEmployRoleDO.getRoleId());
        }
        Iterable iterable = (Iterable)ids.iterator();
        List<BaseRoleDO> result = (List<BaseRoleDO>)baseRoleDao.findAll(iterable);
        return result;
    }
    /**
     * 删除用户角色
     * 根据Id删除用户角色
     * @param id
     * @return
     */
@ -101,4 +114,39 @@ public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRol
        }
    }
    /**
     * 根据用户Id和角色id删除用户角色
     * @param employId
     * @param roleIds
     * @return
     */
    @Transactional
    public void deleteBaseEmployRoleDO(String employId,String roleIds){
        try{
            this.employRoleDao.deleteOneByEmployIdAndRoleId(employId,roleIds);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
    /**
     * 批量删除用户角色
     * @param employId
     * @param roleIds
     * @return
     */
    @Transactional
    public void deleteBatchBaseEmployRoleDO(String employId,String roleIds){
        try{
            this.employRoleDao.deleteManyByEmployIdAndRoleIds(employId,roleIds);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
}

+ 29 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployService.java

@ -9,6 +9,7 @@ import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@ -19,7 +20,10 @@ import java.util.List;
 * Created by chenweida on 2017/5/11.
 * 用户信息功能
 */
@Service
@EnableCaching
@CacheConfig(cacheNames = "employ")
public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
    @Autowired
    private EmployDao employDao;
@ -29,6 +33,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * @param employeeDO
     * @return
     */
    @Cacheable(value = "employ#600#300")
    @Transactional
    public BaseEmployDO createBaseEmployDO(BaseEmployDO employeeDO){
        if (StringUtils.isEmpty(employeeDO.getId())) {
@ -45,6 +50,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * @param employeeDO
     * @return
     */
    @CachePut(value = "employ#600#300",key = "#employeeDO.id")
    @Transactional
    public BaseEmployDO updateBaseEmployDO(BaseEmployDO employeeDO){
        if (StringUtils.isEmpty(employeeDO.getId())) {
@ -61,6 +67,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * @param id
     * @return
     */
    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
    public BaseEmployDO findById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null,ExceptionCode.common_error_params_code);
@ -72,11 +79,31 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
        return BaseEmployDO;
    }
    /**
     * 根据手机号和saasId查询用户,一个用户可能注册多个saas平台,所以根据手机号查找要限定saasId
     * @param phone
     * @param saasId
     * @return
     */
    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
    public BaseEmployDO findByPhoneAndSaasId(String phone,String saasId){
        if (StringUtils.isEmpty(phone)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
        BaseEmployDO BaseEmployDO = this.employDao.findByPhoneAndSaasId(phone,saasId);
        if (null == BaseEmployDO) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
        }
        return BaseEmployDO;
    }
    /**
     * 查询某saasId平台下的所有用户
     * @param saasId
     * @return
     */
    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
    public List<BaseEmployDO> findAllBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
@ -93,6 +120,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * @param saasId
     * @return
     */
    @Cacheable(value = "employ#600#300",key = "#employeeDO.id")
    public List<BaseEmployDO> findAllByNameAndSaasId(String name,String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
@ -109,6 +137,7 @@ public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
     * 根据Id删除用户
     * @param employDO
     */
    @CacheEvict(key = "#employDO.id")
    @Transactional
    public void deleteBaseEmploy(BaseEmployDO employDO){
        if (StringUtils.isEmpty(employDO.getId())) {

+ 60 - 3
web-gateway/src/main/java/com/yihu/jw/controller/base/user/EmployController.java

@ -113,9 +113,9 @@ public class EmployController extends EnvelopRestController {
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseRole.api_getListNoPage)
    @GetMapping(value = BaseUserContants.Employee.api_getListNoPage)
    @ApiOperation(value = "获取功能列表,不分页")
    public Envelop getListNoPage(
    public Envelop getRolesListNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,sex,phone,email,jxzc,lczcn,xlzc,xzzc,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
@ -129,7 +129,64 @@ public class EmployController extends EnvelopRestController {
                filterStr+="saasId="+jsonResult.get("saasId")+";";
            }
        }
        return fegin.getListNoPage(fields, filterStr, sorts);
        return fegin.getRoleList(fields);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.Employee.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增用戶角色", notes = "新增用戶角色")
    public Envelop createEmployRoles(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.Employee.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增用戶角色", notes = "新增用戶角色")
    public Envelop updateEmployRoles(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.Employee.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增用戶角色", notes = "新增用戶角色")
    public Envelop deleteEmployRoles(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.Employee.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增用戶角色", notes = "新增用戶角色")
    public Envelop getRoleList(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
}

+ 20 - 6
web-gateway/src/main/java/com/yihu/jw/feign/base/user/EmployFeign.java

@ -20,19 +20,19 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping(value = BaseRequestMapping.api_base_common)
public interface EmployFeign {
    @RequestMapping(value = BaseUserRequestMapping.BaseRole.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    @RequestMapping(value = BaseUserRequestMapping.BaseEmploy.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop create(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseRole.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    @RequestMapping(value =  BaseUserRequestMapping.BaseEmploy.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    Envelop update(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseRole.api_delete,method = RequestMethod.DELETE)
    @RequestMapping(value =  BaseUserRequestMapping.BaseEmploy.api_delete,method = RequestMethod.DELETE)
    Envelop delete(@PathVariable String id) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getById)
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getById)
    Envelop findById(@PathVariable(value = "id", required = true) String id) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseRole.api_getList, method = RequestMethod.GET)
    @RequestMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList, method = RequestMethod.GET)
    Envelop getList(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
@ -40,9 +40,23 @@ public interface EmployFeign {
            @RequestParam(value = "size", required = false) int size,
            @RequestParam(value = "page", required = false) int page) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getListNoPage)
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getListNoPage)
    Envelop getListNoPage(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseEmployRole.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop createEmployRoles(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseEmployRole.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop updateEmployRoles(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseEmployRole.api_delete,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop deleteEmployRoles(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseEmployRole.api_getListNoPage,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop getRoleList(@RequestBody String jsonData) throws JiWeiException;
}