Explorar el Código

脚手架工程代码精简@20210225:Spring Session相关代码下沉至ipu-restful

huangbo %!s(int64=4) %!d(string=hace) años
padre
commit
88ffbea324

+ 1 - 3
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/RestScaffoldStart.java

@ -2,11 +2,9 @@ package com.ai.ipu.server;
2 2
3 3
4 4
import com.ai.ipu.basic.util.IpuBaseException;
5
import com.ai.ipu.basic.util.IpuUtility;
6 5
import com.ai.ipu.restful.InterceptorManager;
7 6
import com.ai.ipu.restful.boot.IpuRestApplication;
8 7
import com.ai.ipu.restful.interceptor.SessionInterceptor;
9
import com.ai.ipu.server.framework.DefineSessionInterceptor;
10 8
import com.ai.ipu.server.handler.AuthHandler;
11 9
import com.ai.ipu.server.handler.HandlerManager;
12 10
/**
@ -51,7 +49,7 @@ public class RestScaffoldStart {
51 49
    
52 50
    private static void registerInterceptor(){
53 51
        // 注册Session校验拦截器
54
        InterceptorManager.registerHandlerInterceptor("/**", new DefineSessionInterceptor());
52
        InterceptorManager.registerHandlerInterceptor("/**", new SessionInterceptor());
55 53
        // 排除Session校验拦截器的拦截请求
56 54
        String[] excludePaths = new String[]{"/login"};
57 55
        InterceptorManager.registerExcludePath("/**", excludePaths);

+ 0 - 57
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/config/RedisSessionInterceptor.java

@ -1,57 +0,0 @@
1
package com.ai.ipu.server.config;
2

3

4
import javax.servlet.http.HttpServletRequest;
5
import javax.servlet.http.HttpServletResponse;
6

7
import org.slf4j.Logger;
8
import org.slf4j.LoggerFactory;
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.http.HttpStatus;
11
import org.springframework.web.servlet.HandlerInterceptor;
12
import org.springframework.web.servlet.ModelAndView;
13

14
import com.ai.ipu.basic.util.IpuException;
15
import com.ai.ipu.server.util.RedisUtil;
16

17

18
/**
19
 * 登录状态拦截器RedisSessionInterceptor
20
 */
21
public class RedisSessionInterceptor implements HandlerInterceptor {
22
	private static final Logger log = LoggerFactory.getLogger(RedisSessionInterceptor.class);
23
    @Autowired
24
    private RedisUtil redisUtil;
25

26
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
27
			throws Exception {
28
		// 无论访问的地址是不是正确的,都进行登录验证,登录成功后的访问再进行分发,404的访问自然会进入到错误控制器中
29
		/*if (redisUtil.getSessionId(request) != null) {
30
			try {
31
				// 验证当前请求的session是否是已登录的session
32
				String loginSessionId = (String) redisUtil.getRedisSessionId(request);
33
				System.out.println("用户已登录,sessionId为: " + loginSessionId);
34
				if (redisUtil.isValidSession(request)) {
35
					return true;
36
				}
37
			} catch (Exception e) {
38
				log.error(e.getMessage(), e);
39
			}
40
		}
41
		throw new IpuException(HttpStatus.UNAUTHORIZED+"-用户未登录!");*/
42
	    return true;
43
	}
44

45
	
46
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
47
			ModelAndView modelAndView) throws Exception {
48
        
49
	}
50

51
	@Override
52
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
53
			throws Exception {
54

55
	}
56
	
57
}

+ 0 - 26
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/config/WebSecurityConfig.java

@ -1,26 +0,0 @@
1
package com.ai.ipu.server.config;
2

3
import org.springframework.context.annotation.Bean;
4
import org.springframework.context.annotation.Configuration;
5
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
6
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
7

8
/**
9
 * Session配置拦截器
10
 */
11
@Configuration
12
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
13

14
    @Bean
15
	public RedisSessionInterceptor getSessionInterceptor() {
16
		return new RedisSessionInterceptor();
17
	}
18
    
19
	public void addInterceptors(InterceptorRegistry registry) {
20
		// 所有访问都要进入RedisSessionInterceptor拦截器进行登录验证,并排除login接口(全路径)。必须写成链式,分别设置的话会创建多个拦截器。
21
		// 必须写成getSessionInterceptor(),否则SessionInterceptor中的@Autowired会无效
22
		registry.addInterceptor(getSessionInterceptor()).addPathPatterns("/**").excludePathPatterns("/login");
23
		super.addInterceptors(registry);
24
	}
25

26
}

+ 0 - 45
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/DefineSessionInterceptor.java

@ -1,45 +0,0 @@
1
package com.ai.ipu.server.framework;
2

3
import javax.servlet.http.HttpServletRequest;
4
import javax.servlet.http.HttpServletResponse;
5
import javax.servlet.http.HttpSession;
6

7
import org.springframework.http.HttpStatus;
8
import org.springframework.web.servlet.HandlerInterceptor;
9
import org.springframework.web.servlet.ModelAndView;
10

11
import com.ai.ipu.basic.util.IpuUtility;
12

13
//@Slf4j
14
public class DefineSessionInterceptor implements HandlerInterceptor{
15

16
    @Override
17
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
18
            throws Exception {
19
        String ipuSessionId = SpringSessionManager.getIpuSessionId();
20
        if(ipuSessionId==null){
21
            // 404会进入错误控制器
22
            IpuUtility.error(HttpStatus.UNAUTHORIZED+"-用户未登录!");
23
        }
24
        
25
        HttpSession session = request.getSession();
26
        String _ipuSessionId = (String) session.getAttribute(SpringSessionManager.IPU_SESSION_ID);
27
        if(!ipuSessionId.equals(_ipuSessionId)){
28
            IpuUtility.error(HttpStatus.UNAUTHORIZED+"-用户登录失效!");
29
        }
30
        return true;
31
    }
32

33
    @Override
34
    public void postHandle(HttpServletRequest userRequest, HttpServletResponse userResponse, Object userHandler,
35
            ModelAndView userModelAndView) throws Exception {
36
        
37
    }
38

39
    @Override
40
    public void afterCompletion(HttpServletRequest userRequest, HttpServletResponse userResponse, Object userHandler,
41
            Exception userEx) throws Exception {
42
        
43
    }
44

45
}

+ 0 - 22
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/ISessionManager.java

@ -1,22 +0,0 @@
1
package com.ai.ipu.server.framework;
2

3
import java.util.Map;
4

5
import com.ai.ipu.server.framework.context.IContext;
6

7
/**
8
 * @author huangbo@asiainfo.com
9
 * @team IPU
10
 * @date 2021年2月23日下午3:40:32
11
 * @desc Session管理
12
 */
13
public interface ISessionManager {
14

15
    public String create(IContext context) throws Exception;
16

17
    public void verify(String sessionId, Map<String, Object> param) throws Exception;
18
    
19
    public String update(String sessionId, IContext context) throws Exception;
20

21
    public String destory(String sessionId) throws Exception;
22
}

+ 0 - 117
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/SessionManager.java

@ -1,117 +0,0 @@
1
package com.ai.ipu.server.framework;
2

3
import java.util.Map;
4

5
import javax.servlet.http.HttpSession;
6

7
import org.slf4j.Logger;
8
import org.slf4j.LoggerFactory;
9

10
import com.ai.ipu.restful.web.ServletManager;
11
import com.ai.ipu.server.framework.context.IContext;
12
import com.ai.ipu.server.framework.session.DefaultSession;
13
import com.ai.ipu.server.framework.session.ISession;
14
import com.ai.ipu.server.util.SpringUtil;
15

16
/**
17
 * @author huangbo@asiainfo.com
18
 * @team IPU
19
 * @date 2021年2月23日上午11:03:13
20
 * @desc Session管理
21
 */
22
public class SessionManager implements ISessionManager{
23
    private static final Logger log = LoggerFactory.getLogger(SessionManager.class);
24
    private static int sessionTimeout = 3000;
25
    private static String IPU_SESSION_ID = "IpuSessionId";
26
    
27
    private SpringRedisCache springRedisCache;
28
    
29
    private volatile static ISessionManager instance;
30
    
31
    private SessionManager() {
32
        springRedisCache = SpringUtil.getBean(SpringRedisCache.class);
33
    }
34
    
35
    public static ISessionManager getInstance() throws Exception {
36
        if (instance == null) {
37
            synchronized (SessionManager.class) {
38
                if (instance == null) {
39
                    instance = new SessionManager();
40
                }
41
            }
42
        }
43
        return instance;
44
    }
45

46
    @Override
47
    public String create(IContext context) throws Exception {
48
        String sessionId = createSessionId();
49
        ISession session = createSession(context);
50
        springRedisCache.put(sessionId, session, sessionTimeout);
51
        
52
        HttpSession httpSession = ServletManager.getSession();
53
        httpSession.setAttribute(IPU_SESSION_ID, sessionId);
54
        return sessionId;
55
    }
56

57
    @Override
58
    public void verify(String sessionId, Map<String, Object> param) throws Exception {
59
        
60
    }
61

62
    @Override
63
    public String update(String sessionId, IContext context) throws Exception {
64
        Object element = springRedisCache.get(sessionId);
65
        context.setDirty(false);
66
        if (element == null) {
67
            if(log.isDebugEnabled()){
68
                log.debug("No Cached Element[{}]!", sessionId);
69
            }
70
            springRedisCache.put(sessionId, createSession(context));
71
        }else{
72
            ISession session = (DefaultSession)element;
73
            session.setContext(context, System.currentTimeMillis()); //分布式环境下,时间戳统一获取
74
            springRedisCache.put(sessionId, session);
75
        }
76
        return sessionId;
77
    }
78

79
    @Override
80
    public String destory(String sessionId) throws Exception {
81
        Object session = springRedisCache.get(sessionId);
82
        if (session == null) {
83
            if(log.isDebugEnabled()){
84
                log.debug("No Cached Element[{}]!", sessionId);
85
            }
86
            return null;
87
        }
88
        springRedisCache.remove(sessionId);
89
        return sessionId;
90
    }
91

92
    private String createSessionId(){
93
        return getRandomNumber(4)+String.valueOf(System.currentTimeMillis());
94
    }
95
    
96
    private ISession createSession(IContext context){
97
        return new DefaultSession(context, System.currentTimeMillis());
98
    }
99
    
100
    private static final String[] NUM = {"0","1","2","3","4","5","6","7","8","9"};
101
    private static final int NUMBER_TEN = 10;
102
    
103
    /**
104
     * 获取len长度的随机数
105
     * @param len 长度
106
     * @return String 随机数
107
     */
108
    public static String getRandomNumber(int len){
109
        String randomCode = "";
110
        for(int i = 0; i < len; i++){
111
            int number = (int) (Math.random() * NUMBER_TEN);
112
            randomCode += NUM[number];
113
        }
114
        return randomCode;
115
    }
116
    
117
}

+ 0 - 74
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/SpringRedisCache.java

@ -1,74 +0,0 @@
1
package com.ai.ipu.server.framework;
2

3
import java.util.concurrent.TimeUnit;
4

5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.data.redis.core.RedisTemplate;
7
import org.springframework.stereotype.Component;
8

9
import com.ai.ipu.basic.util.IpuUtility;
10
import com.ai.ipu.cache.ICache;
11

12
/**
13
 * @author huangbo@asiainfo.com
14
 * @team IPU
15
 * @date 2021年2月24日下午5:52:32
16
 * @desc Spring体系下载Redis操作
17
 * 可以考虑使用StringRedisTemplate代替RedisTemplate
18
 */
19
@Component
20
public class SpringRedisCache implements ICache {
21
    @Autowired
22
    private RedisTemplate<Object, Object> redisTemplate;
23
    
24
    @Override
25
    public boolean put(Object key, Object value) throws Exception {
26
        redisTemplate.opsForValue().set(key, value);
27
        return true;
28
    }
29

30
    @Override
31
    public Object get(Object key) throws Exception {
32
        return redisTemplate.opsForValue().get(key);
33
    }
34

35
    @Override
36
    public boolean remove(Object key) throws Exception {
37
        redisTemplate.delete(key);
38
        return true;
39
    }
40

41
    @Override
42
    public void clear() throws Exception {
43
        IpuUtility.error("SpringRedisCache无clear方法的实现");
44
    }
45

46
    @Override
47
    public boolean keyExists(String cacheKey) {
48
        return redisTemplate.hasKey(cacheKey);
49
    }
50

51
    @Override
52
    public boolean put(Object key, Object value, int secondTimeout) throws Exception {
53
        redisTemplate.opsForValue().set(key, value, secondTimeout, TimeUnit.SECONDS);
54
        return true;
55
    }
56

57
    @Override
58
    public void close() throws Exception {
59
        IpuUtility.error("SpringRedisCache无close方法的实现");
60
    }
61

62
    public RedisTemplate<Object, Object> getRedisTemplate() {
63
        return redisTemplate;
64
    }
65
}
66

67
/**
68
 *  Redis常见的五大数据类型:
69
 *  stringRedisTemplate.opsForValue();[String(字符串)]
70
 *  stringRedisTemplate.opsForList();[List(列表)]
71
 *  stringRedisTemplate.opsForSet();[Set(集合)]
72
 *  stringRedisTemplate.opsForHash();[Hash(散列)]
73
 *  stringRedisTemplate.opsForZSet();[ZSet(有序集合)]
74
 */

+ 0 - 80
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/SpringSessionManager.java

@ -1,80 +0,0 @@
1
package com.ai.ipu.server.framework;
2

3
import javax.servlet.http.HttpSession;
4

5
import org.springframework.data.redis.core.RedisTemplate;
6

7
import com.ai.ipu.restful.web.ServletManager;
8
import com.ai.ipu.server.util.SpringUtil;
9

10
public class SpringSessionManager {
11
    private static final String IPU_ROOT_DIR = "ipu";
12
    public static final String IPU_SESSION_ID = "IpuSessionId";
13
    private static final String IPU_ACCOUNT = "IpuAccount";
14
    private static final String IPU_CONTEXT = "IpuContext";
15
    private static final SpringRedisCache springRedisCache;
16
    static {
17
        springRedisCache = SpringUtil.getBean(SpringRedisCache.class);
18
    }
19
    
20
    public static String createIpuSession(String account, Object context) throws Exception{
21
        // 清除ipuSessionId
22
        clearIpuSession(account);
23
        // 创建ipuSessionId
24
        String ipuSessionId = SessionManager.getRandomNumber(4) + String.valueOf(System.currentTimeMillis());
25
        // Spring Session中存储对应信息
26
        HttpSession httpSession = ServletManager.getSession();
27
        httpSession.setAttribute(IPU_SESSION_ID, ipuSessionId);
28
        httpSession.setAttribute(IPU_ACCOUNT, account);
29
        httpSession.setAttribute(IPU_CONTEXT, context);
30
        
31
        springRedisCachePut(account, ipuSessionId);
32
        springRedisCachePut(ipuSessionId, httpSession.getId()); //将sessionId存储为后续清除动作提供key
33
        
34
        return ipuSessionId;
35
    }
36
    
37
    public static void clearIpuSession(String account) throws Exception {
38
        // 清除Spring Redis Session中的冗余数据,重启客户端时
39
        String ipuSessionId = (String) springRedisCacheGet(account);
40
        if(ipuSessionId==null||"".equals(ipuSessionId)){
41
            return;
42
        }
43
        String sessionId = (String) springRedisCacheGet(ipuSessionId);
44
        /*
45
         * 补充清除逻辑:根据sessionId来清除Spring Redis Session
46
         */
47
        springRedisCacheRemove(ipuSessionId);
48
        springRedisCacheRemove(account);
49
    }
50

51
    public static String getIpuSessionId() throws Exception {
52
        HttpSession httpSession = ServletManager.getSession();
53
        String account = (String) httpSession.getAttribute(IPU_ACCOUNT);
54
        if(account==null){
55
            return null;
56
        }
57
        return (String) springRedisCacheGet(account);
58
    }
59
    
60
    public static String getSessionAttr(String attrKey) {
61
        HttpSession httpSession = ServletManager.getSession();
62
        String sessionKey ="spring:session:sessions:" + httpSession.getId();
63
        
64
        RedisTemplate<Object, Object> redisTemplate = springRedisCache.getRedisTemplate();
65
        String ipuSessionId = (String) redisTemplate.opsForHash().get(sessionKey, "sessionAttr:" + attrKey);
66
        return ipuSessionId;
67
    }
68
    
69
    private static void springRedisCachePut(String key, Object value){
70
        springRedisCache.getRedisTemplate().opsForHash().put(IPU_ROOT_DIR, key, value);
71
    }
72
    
73
    private static Object springRedisCacheGet(String key){
74
        return springRedisCache.getRedisTemplate().opsForHash().get(IPU_ROOT_DIR, key);
75
    }
76
    
77
    private static void springRedisCacheRemove(String key){
78
        springRedisCache.getRedisTemplate().opsForHash().delete(IPU_ROOT_DIR, key);
79
    }
80
}

+ 0 - 51
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/context/DefaultContext.java

@ -1,51 +0,0 @@
1
package com.ai.ipu.server.framework.context;
2

3
import java.util.HashMap;
4
import java.util.Map;
5

6
/**
7
 * @author huangbo@asiainfo.com
8
 * @team IPU
9
 * @date 2021年2月23日上午11:31:40
10
 * @desc 上下文默认实现类
11
 */
12
public class DefaultContext implements IContext {
13
    
14
    private boolean isDirty; //上下文变脏可能需要回存
15
    
16
    private Map<String, Object> data;
17
    
18
    public DefaultContext(Map<String, Object> data) {
19
        this.data = data;
20
        if(this.data==null){
21
            this.data = new HashMap<String, Object>();
22
        }
23
    }
24

25
    @Override
26
    public void put(String key, Object value) {
27
        data.put(key, value);
28
        setDirty(true);
29
    }
30

31
    @Override
32
    public Object get(String key) {
33
        return data.get(key);
34
    }
35

36
    @Override
37
    public boolean isDirty() {
38
        return isDirty;
39
    }
40

41
    @Override
42
    public void setDirty(boolean isDirty) {
43
        this.isDirty = isDirty;
44
    }
45

46
    @Override
47
    public Map<String, Object> getData() {
48
        return data;
49
    }
50

51
}

+ 0 - 24
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/context/IContext.java

@ -1,24 +0,0 @@
1
package com.ai.ipu.server.framework.context;
2

3
import java.util.Map;
4

5
/**
6
 * @author huangbo@asiainfo.com
7
 * @team IPU
8
 * @date 2021年2月23日上午11:15:09
9
 * @desc 上下文抽象接口,定义上下文的行文
10
 * 放弃对DTO的存储和映射
11
 */
12
public interface IContext {
13

14
    public void put(String key, Object value);
15
    
16
    public Object get(String key);
17
    
18
    public boolean isDirty();
19
    
20
    public void setDirty(boolean isDirty);
21
    
22
    public Map<String,Object> getData();
23
    
24
}

+ 0 - 64
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/session/DefaultSession.java

@ -1,64 +0,0 @@
1
package com.ai.ipu.server.framework.session;
2

3
import com.ai.ipu.server.framework.context.DefaultContext;
4
import com.ai.ipu.server.framework.context.IContext;
5
import com.alibaba.fastjson.JSON;
6
import com.alibaba.fastjson.serializer.SerializerFeature;
7

8
public class DefaultSession implements ISession {
9
    private static final long serialVersionUID = 2077082727127850649L;
10

11
    private String contextData;
12
    
13
    private long latestTime;
14
    private long creatTime;
15
    private long timeoutInterval;
16
    
17
    public DefaultSession(IContext context, long latestTime) {
18
        contextData = JSON.toJSONString(context, SerializerFeature.IgnoreNonFieldGetter);
19
        this.latestTime = latestTime;
20
    }
21

22
    @Override
23
    public IContext getContext() {
24
        IContext context = JSON.toJavaObject(JSON.parseObject(contextData), DefaultContext.class);
25
        return context;
26
    }
27
    
28
    @Override
29
    public void setContext(IContext context, long latestTime) {
30
        contextData = JSON.toJSONString(context, SerializerFeature.IgnoreNonFieldGetter);
31
        this.latestTime = latestTime;
32
    }
33

34
    @Override
35
    public long getLatestTime() {
36
        return latestTime;
37
    }
38

39
    @Override
40
    public void setLatestTime(long latestTime) {
41
        this.latestTime = latestTime;
42
    }
43

44
    @Override
45
    public long getCreatTime() {
46
        return creatTime;
47
    }
48

49
    @Override
50
    public void setCreatTime(long creatTime) {
51
        this.creatTime = creatTime;
52
    }
53

54
    @Override
55
    public long getTimeoutInterval() {
56
        return timeoutInterval;
57
    }
58

59
    @Override
60
    public void setTimeoutInterval(long timeoutInterval) {
61
        this.timeoutInterval = timeoutInterval;
62
    }
63

64
}

+ 0 - 40
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/framework/session/ISession.java

@ -1,40 +0,0 @@
1
package com.ai.ipu.server.framework.session;
2

3
import java.io.Serializable;
4

5
import com.ai.ipu.server.framework.context.IContext;
6

7
/**
8
 * @author huangbo@asiainfo.com
9
 * @team IPU
10
 * @date 2021年2月24日下午6:12:24
11
 * @desc Session对象为一级缓存,Context为二级缓存并存储在Session中。
12
 * 参考Spring Session,引入lastAccessedTime、creationTime、maxInactiveInterval属性
13
 */
14
public interface ISession extends Serializable{
15

16
    /**获取上下文数据*/
17
    public IContext getContext();
18
    
19
    /**设置上下文数据*/
20
    public void setContext(IContext context, long latestTime);
21
    
22
    /**获取最新访问时间*/
23
    public long getLatestTime();
24
    
25
    /**设置最新访问时间*/
26
    public void setLatestTime(long latestTime);
27
    
28
    /**获取创建时间*/
29
    public long getCreatTime();
30
    
31
    /**设置创建时间*/
32
    public void setCreatTime(long creatTime);
33
    
34
    /**获取超时间隔*/
35
    public long getTimeoutInterval();
36
    
37
    /**设置超时间隔*/
38
    public void setTimeoutInterval(long timeoutInterval);
39
    
40
}

+ 1 - 1
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/service/impl/AuthServiceImpl.java

@ -5,7 +5,7 @@ import java.util.Map;
5 5

6 6
import org.springframework.stereotype.Service;
7 7

8
import com.ai.ipu.server.framework.SpringSessionManager;
8
import com.ai.ipu.restful.framework.SpringSessionManager;
9 9
import com.ai.ipu.server.handler.AuthHandler;
10 10
import com.ai.ipu.server.handler.HandlerManager;
11 11
import com.ai.ipu.server.service.AuthService;

+ 0 - 111
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/util/RedisOperUtil.java

@ -1,111 +0,0 @@
1
package com.ai.ipu.server.util;
2

3

4
import java.util.concurrent.TimeUnit;
5

6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.data.redis.core.RedisTemplate;
8
import org.springframework.data.redis.core.StringRedisTemplate;
9
import org.springframework.stereotype.Component;
10

11
import com.ai.ipu.basic.string.StringUtil;
12
import com.ai.ipu.basic.util.IpuUtility;
13

14
import com.ai.ipu.cache.ICache;
15

16
@Component
17
public class RedisOperUtil implements ICache{
18
    @Autowired
19
    private StringRedisTemplate strRedisTemplate;
20
    @Autowired
21
    private RedisTemplate redisTemplate;
22
   /**
23
     *  Redis常见的五大数据类型:
24
     *  stringRedisTemplate.opsForValue();[String(字符串)]
25
     *  stringRedisTemplate.opsForList();[List(列表)]
26
     *  stringRedisTemplate.opsForSet();[Set(集合)]
27
     *  stringRedisTemplate.opsForHash();[Hash(散列)]
28
     *  stringRedisTemplate.opsForZSet();[ZSet(有序集合)]
29
     */
30
       
31
    
32
    /**
33
     * 存
34
     */
35
    public boolean put(Object key, Object value) throws Exception {
36
        boolean result = true;
37
        try{
38
            if (key instanceof String)
39
            	strRedisTemplate.opsForValue().set(key.toString(), String.valueOf(value));
40
            else
41
            	IpuUtility.error("key只支持String,保存数据到缓存操作失败"); 
42
        }catch (NullPointerException e)
43
		{
44
			if (StringUtil.isEmpty((String)key))
45
				IpuUtility.error("由于key值为空,导致保存数据到缓存操作失败", e);
46
			IpuUtility.error("由于value值为空,导致保存数据到缓存操作失败", e);
47
			result = false;
48
		}
49
        return result;
50
    }
51

52
    /**
53
     * 取
54
     */
55
    public Object get(Object key) throws Exception {
56
        return strRedisTemplate.opsForValue().get(key);
57
    }
58

59
    /**
60
     * 移除
61
     */
62
    public boolean remove(Object key) throws Exception {
63
    	redisTemplate.delete(key);
64
    	return true;
65
    }
66

67
    /**
68
     * 清除
69
     */
70
    public void clear() throws Exception {
71
    	;
72
    }
73

74
    /**
75
     * key是否存在
76
     */
77
    public boolean keyExists(String key) {
78
        return strRedisTemplate.hasKey(key);
79
    }
80

81
    /**
82
     * 设置数据
83
     * @param key
84
     * @param value
85
     * @param timeoutSeconds
86
     * @return
87
     * @throws Exception
88
     */
89
    public boolean put(Object key, Object value, int timeoutSeconds) throws Exception {
90
        boolean result = true;
91
        try {
92
            if (key instanceof String)
93
            	strRedisTemplate.opsForValue().set(key.toString(), String.valueOf(value), timeoutSeconds, TimeUnit.SECONDS);
94
            else
95
            	IpuUtility.error("key只支持String,保存数据到缓存操作失败"); 
96
        }catch (NullPointerException e)
97
		{
98
			if (StringUtil.isEmpty((String)key))
99
				IpuUtility.error("由于key值为空,导致保存数据到缓存操作失败", e);
100
			IpuUtility.error("由于value值为空,导致保存数据到缓存操作失败", e);
101
			result = false;
102
		}
103
        return result;
104
    }
105

106
    public void close() throws Exception {
107
    	;
108
    }
109

110

111
}

+ 0 - 129
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/util/RedisUtil.java

@ -1,129 +0,0 @@
1
package com.ai.ipu.server.util;
2

3
import java.util.List;
4
import java.util.Map;
5

6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpSession;
8

9
import org.jsoup.helper.StringUtil;
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.stereotype.Component;
12

13
import com.ai.ipu.basic.util.IpuException;
14
import com.ai.ipu.cache.CacheFactory;
15
import com.ai.ipu.cache.config.IpuCacheConfig;
16
import com.ai.ipu.cache.util.IpuCacheConstant;
17

18
@Component
19
public class RedisUtil{    
20
    private static final String DEFAULT_CACHE_NAME = "ssn";
21
    @Autowired
22
    private RedisOperUtil redis;
23
    
24
	public static String[] initRedis(String[] args) throws Exception {
25
		//将ipu-cache配置作为springboot配置
26
		String[] argv = new String[args.length+9];
27
        String cacheName = DEFAULT_CACHE_NAME;
28
		int i=0;		
29
		for (String arg : args) {
30
			if (arg.contains("--redis.cache.name")&&arg.contains("=")) {
31
				cacheName = arg.substring(arg.indexOf("=")+1);
32
				argv[i++] = " ";
33
			}
34
			else
35
				argv[i++] = arg;
36
		}
37
		String cacheType = IpuCacheConfig.getCacheType(cacheName);
38
		if (!CacheFactory.DEFAULT_CACHE_TYPE.endsWith(cacheType))
39
			throw new IpuException("只支持redis保存spring session信息!请检查ipu-cache.xml里的type");
40
		
41
		String jedisType = IpuCacheConfig.getCacheDefaultAttr(cacheName,
42
                IpuCacheConstant.Redis.CLIENT_TYPE, IpuCacheConstant.ClientType.JEDIS_CLIENT);
43
		
44
		argv[i++] = "--spring.session.store-type="+CacheFactory.DEFAULT_CACHE_TYPE;
45
		List<Map<String,String>> clusterList = IpuCacheConfig.getCacheServers(cacheName);
46
        if (null == clusterList || clusterList.isEmpty())
47
            throw new IllegalArgumentException("请确认ipu-cache.xml里server是否配置正确");
48
        
49
		if (IpuCacheConstant.ClientType.JEDIS_CLIENT.equalsIgnoreCase(jedisType))
50
        {
51
        	//只取第一个redis地址
52
            Map<String, String> server = clusterList.get(0);
53
        	argv[i++] = "--spring.redis.database=0";
54
        	argv[i++] = "--spring.redis.host=" + server.get(IpuCacheConstant.Redis.IP);
55
        	argv[i++] = "--spring.redis.port=" + server.get(IpuCacheConstant.Redis.PORT);
56
        }
57
        else
58
        {
59
        	//拼集群节点
60
        	StringBuffer nodes = new StringBuffer();
61
        	Map<String, String> server;
62
        	int j=0;
63
            for (; j < clusterList.size(); j++) {
64
                server = clusterList.get(j);
65
                if (j == clusterList.size()-1)
66
                    nodes.append(server.get(IpuCacheConstant.Redis.IP)).append(":").append(server.get(IpuCacheConstant.Redis.PORT));
67
                else
68
                	nodes.append(server.get(IpuCacheConstant.Redis.IP)).append(":").append(server.get(IpuCacheConstant.Redis.PORT)).append(",");
69
            }
70
    		argv[i++] = "--spring.redis.cluster.nodes=" + nodes.toString();
71
    		argv[i++] = "--spring.redis.cluster.timeout=5";
72
    		argv[i++] = "--spring.redis.cluster.max-redirects=3";
73
        }
74

75
		//设置访问密码
76
		String auth = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.AUTH);
77
        if (StringUtil.isBlank(auth))
78
        	argv[i++] = "--spring.redis.password= ";
79
        else
80
        	argv[i++] = "--spring.redis.password=" + auth;
81
        
82
        //设置连接池参数
83
        int poolSize = IpuCacheConstant.RedisConstant.DEFAULT_POOL_SIZE;
84
        int maxIdle  = IpuCacheConstant.RedisConstant.DEFAULT_MAX_IDLE;
85
        int minIdle  = IpuCacheConstant.RedisConstant.DEFAULT_MIN_IDLE;
86
        
87
        String strPoolSize = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.POOL_SIZE);
88
        String strMaxIdle = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.MAX_IDLE);
89
        String strMinIdle = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.MIN_IDLE);        
90
        if(!StringUtil.isBlank(strPoolSize)){
91
            poolSize = Integer.parseInt(strPoolSize);
92
        }
93
        if (!StringUtil.isBlank(strMaxIdle)){
94
            maxIdle = Integer.parseInt(strMaxIdle);
95
        }
96
        if (!StringUtil.isBlank(strMinIdle)){
97
            minIdle = Integer.parseInt(strMinIdle);
98
        }
99
		argv[i++] = "--spring.redis.pool.max-active=" + poolSize;
100
		argv[i++] = "--spring.redis.pool.max-idle=" + maxIdle;
101
		argv[i++] = "--spring.redis.pool.max-wait=-1";
102
		argv[i++] = "--spring.redis.pool.min-idle=" + minIdle;
103

104
        return argv;        
105
	}
106
	
107
	public Object getSessionId(HttpServletRequest request) {
108
		HttpSession session = request.getSession();
109
		return session.getAttribute("loginSessionId");
110
	}	
111
	
112
	public void saveSessionId(HttpServletRequest request, Object sessionId) throws Exception {
113
		HttpSession session = request.getSession();
114
		session.setAttribute("loginSessionId", sessionId);
115
		redis.put("loginUser:"+sessionId, session.getId());
116
	}	
117
	
118
	public Object getRedisSessionId(HttpServletRequest request) throws Exception {
119
		String sessionId = (String)getSessionId(request);
120
		return redis.get("loginUser:"+sessionId);
121
	}	
122
	
123
	public boolean isValidSession(HttpServletRequest request) throws Exception {
124
		HttpSession session = request.getSession();
125
		String sessionId = (String)getSessionId(request);
126
		String redisSessionId = (String)redis.get("loginUser:"+sessionId);
127
		return session.getId().equals(redisSessionId)?true:false;
128
	}
129
}