支持 redis和ecache 切换

This commit is contained in:
jamen
2018-02-23 12:44:52 +08:00
parent 496f0ee7d4
commit e40356ef92
17 changed files with 145051 additions and 0 deletions
+52434
View File
File diff suppressed because it is too large Load Diff
+45911
View File
File diff suppressed because one or more lines are too long
+45913
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,37 @@
package com.slife.cache;
/**
* 缓存工厂基类
*/
public abstract class BaseCacheFactory implements ICache {
@Override
@SuppressWarnings("unchecked")
public <T> T get(String cacheName, Object key, ILoader iLoader) {
Object data = get(cacheName, key);
if (data == null) {
data = iLoader.load();
put(cacheName, key, data);
}
return (T) data;
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(String cacheName, Object key, Class<? extends ILoader> iLoaderClass) {
Object data = get(cacheName, key);
if (data == null) {
try {
ILoader dataLoader = iLoaderClass.newInstance();
data = dataLoader.load();
put(cacheName, key, data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return (T) data;
}
}
@@ -0,0 +1,45 @@
package com.slife.cache;
import java.util.List;
/**
* 缓存工具类
*/
public class CacheUtils {
private static ICache defaultCacheFactory = new EhcacheFactory();
public static void put(String cacheName, Object key, Object value) {
defaultCacheFactory.put(cacheName, key, value);
}
public static <T> T get(String cacheName, Object key) {
return defaultCacheFactory.get(cacheName, key);
}
@SuppressWarnings("rawtypes")
public static List getKeys(String cacheName) {
return defaultCacheFactory.getKeys(cacheName);
}
public static void remove(String cacheName, Object key) {
defaultCacheFactory.remove(cacheName, key);
}
public static void removeAll(String cacheName) {
defaultCacheFactory.removeAll(cacheName);
}
public static <T> T get(String cacheName, Object key, ILoader iLoader) {
return defaultCacheFactory.get(cacheName, key, iLoader);
}
public static <T> T get(String cacheName, Object key, Class<? extends ILoader> iLoaderClass) {
return defaultCacheFactory.get(cacheName, key, iLoaderClass);
}
}
@@ -0,0 +1,78 @@
package com.slife.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Ehcache缓存工厂
* @author chen
*/
public class EhcacheFactory extends BaseCacheFactory {
private static CacheManager cacheManager;
private static volatile Object locker = new Object();
private static final Logger log = LoggerFactory.getLogger(EhcacheFactory.class);
private static CacheManager getCacheManager() {
if (cacheManager == null) {
synchronized (EhcacheFactory.class) {
if (cacheManager == null) {
cacheManager = CacheManager.create();
}
}
}
return cacheManager;
}
static Cache getOrAddCache(String cacheName) {
CacheManager cacheManager = getCacheManager();
Cache cache = cacheManager.getCache(cacheName);
if (cache == null) {
synchronized(locker) {
cache = cacheManager.getCache(cacheName);
if (cache == null) {
log.warn("无法找到缓存 [" + cacheName + "]的配置, 使用默认配置.");
cacheManager.addCacheIfAbsent(cacheName);
cache = cacheManager.getCache(cacheName);
log.debug("缓存 [" + cacheName + "] 启动.");
}
}
}
return cache;
}
@Override
public void put(String cacheName, Object key, Object value) {
getOrAddCache(cacheName).put(new Element(key, value));
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(String cacheName, Object key) {
Element element = getOrAddCache(cacheName).get(key);
return element != null ? (T)element.getObjectValue() : null;
}
@Override
@SuppressWarnings("rawtypes")
public List getKeys(String cacheName) {
return getOrAddCache(cacheName).getKeys();
}
@Override
public void remove(String cacheName, Object key) {
getOrAddCache(cacheName).remove(key);
}
@Override
public void removeAll(String cacheName) {
getOrAddCache(cacheName).removeAll();
}
}
+28
View File
@@ -0,0 +1,28 @@
package com.slife.cache;
import java.util.List;
/**
* c
* 通用缓存接口
* @author chen
*/
public interface ICache {
void put(String cacheName, Object key, Object value);
<T> T get(String cacheName, Object key);
@SuppressWarnings("rawtypes")
List getKeys(String cacheName);
void remove(String cacheName, Object key);
void removeAll(String cacheName);
<T> T get(String cacheName, Object key, ILoader iLoader);
<T> T get(String cacheName, Object key, Class<? extends ILoader> iLoaderClass);
}
+10
View File
@@ -0,0 +1,10 @@
package com.slife.cache;
/**
* 数据重载
* @author chen
*/
public interface ILoader {
Object load();
}
@@ -0,0 +1,66 @@
package com.slife.filter;
import com.slife.enums.HttpCodeEnum;
import com.slife.exception.SlifeException;
import com.slife.rest.JwtProperties;
import com.slife.rest.JwtTokenUtil;
import com.slife.util.RenderUtils;
import io.jsonwebtoken.JwtException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 对客户端请求的jwt token验证过滤器
* @author chen
*/
public class AuthFilter extends OncePerRequestFilter {
private final Log logger = LogFactory.getLog(this.getClass());
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtProperties jwtProperties;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//登录地址不做校验
if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
chain.doFilter(request, response);
return;
}
final String requestHeader = request.getHeader(jwtProperties.getHeader());
String authToken = null;
if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
authToken = requestHeader.substring(7);
//验证token是否过期,包含了验证jwt是否正确
try {
boolean flag = jwtTokenUtil.isTokenExpired(authToken);
if (flag) {
RenderUtils.renderJson(response, new SlifeException(HttpCodeEnum.TOKEN_ERR));
return;
}
} catch (JwtException e) {
//有异常就是token解析失败
RenderUtils.renderJson(response, new SlifeException(HttpCodeEnum.TOKEN_ERR));
return;
}
} else {
//header没有带Bearer字段
RenderUtils.renderJson(response, new SlifeException(HttpCodeEnum.TOKEN_ERR));
return;
}
chain.doFilter(request, response);
}
}
@@ -0,0 +1,69 @@
package com.slife.rest;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* jwt相关配置
*
*/
@Configuration
@ConfigurationProperties(prefix = JwtProperties.JWT_PREFIX)
public class JwtProperties {
public static final String JWT_PREFIX = "jwt";
private String header = "Authorization";
private String secret = "defaultSecret";
private Long expiration = 604800L;
private String authPath = "auth";
private String md5Key = "randomKey";
public static String getJwtPrefix() {
return JWT_PREFIX;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public Long getExpiration() {
return expiration;
}
public void setExpiration(Long expiration) {
this.expiration = expiration;
}
public String getAuthPath() {
return authPath;
}
public void setAuthPath(String authPath) {
this.authPath = authPath;
}
public String getMd5Key() {
return md5Key;
}
public void setMd5Key(String md5Key) {
this.md5Key = md5Key;
}
}
@@ -0,0 +1,134 @@
package com.slife.rest;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* <p>jwt token工具类</p>
* <pre>
* jwt的claim里一般包含以下几种数据:
* 1. iss -- token的发行者
* 2. sub -- 该JWT所面向的用户
* 3. aud -- 接收该JWT的一方
* 4. exp -- token的失效时间
* 5. nbf -- 在此时间段之前,不会被处理
* 6. iat -- jwt发布时间
* 7. jti -- jwt唯一标识,防止重复使用
* </pre>
*
*/
@Component
public class JwtTokenUtil {
@Autowired
private JwtProperties jwtProperties;
/**
* 获取用户名从token中
*/
public String getUsernameFromToken(String token) {
return getClaimFromToken(token).getSubject();
}
/**
* 获取jwt发布时间
*/
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token).getIssuedAt();
}
/**
* 获取jwt失效时间
*/
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token).getExpiration();
}
/**
* 获取jwt接收者
*/
public String getAudienceFromToken(String token) {
return getClaimFromToken(token).getAudience();
}
/**
* 获取私有的jwt claim
*/
public String getPrivateClaimFromToken(String token, String key) {
return getClaimFromToken(token).get(key).toString();
}
/**
* 获取md5 key从token中
*/
public String getMd5KeyFromToken(String token) {
return getPrivateClaimFromToken(token, jwtProperties.getMd5Key());
}
/**
* 获取jwt的payload部分
*/
public Claims getClaimFromToken(String token) {
return Jwts.parser()
.setSigningKey(jwtProperties.getSecret())
.parseClaimsJws(token)
.getBody();
}
/**
* 解析token是否正确,不正确会报异常<br>
*/
public void parseToken(String token) throws JwtException {
Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody();
}
/**
* <pre>
* 验证token是否失效
* true:过期 false:没过期
* </pre>
*/
public Boolean isTokenExpired(String token) {
try {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
} catch (ExpiredJwtException expiredJwtException) {
return true;
}
}
/**
* 生成token(通过用户名和签名时候用的随机数)
*/
public String generateToken(String userName, String randomKey) {
Map<String, Object> claims = new HashMap<>();
claims.put(jwtProperties.getMd5Key(), randomKey);
return doGenerateToken(claims, userName);
}
/**
* 生成token
*/
private String doGenerateToken(Map<String, Object> claims, String subject) {
final Date createdDate = new Date();
final Date expirationDate = new Date(createdDate.getTime() + jwtProperties.getExpiration() * 1000);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
.compact();
}
}
@@ -0,0 +1,78 @@
package com.slife.util;
import com.alibaba.fastjson.JSON;
import com.slife.enums.HttpCodeEnum;
import com.slife.exception.SlifeException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
;
/**
* 渲染工具类
*
* @author chen
*/
public class RenderUtils {
/**
* 渲染json对象
*/
public static void renderJson(HttpServletResponse response, Object jsonObject) {
try {
response.setContentType("application/json;charset=UTF-8");
//response.setHeader("content-type", "application/json;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(JSON.toJSONString(jsonObject));
} catch (IOException e) {
throw new SlifeException(HttpCodeEnum.FAIL);
}
}
/**
* 跳转到html页面
*
* @param request
* @param response
*/
public static void renderHtml(HttpServletRequest request, HttpServletResponse response,String html) {
try {
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(html);
} catch (IOException e) {
throw new SlifeException(HttpCodeEnum.FAIL);
}
}
/**
* 跳转到html页面
*
* @param request
* @param response
*/
public static void renderForward(HttpServletRequest request, HttpServletResponse response,String addres) {
try {
request.getRequestDispatcher("/index.html").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
throw new SlifeException(HttpCodeEnum.FAIL);
}
}
public static void renderRedirect(HttpServletRequest request, HttpServletResponse response,String addres) {
try {
response.sendRedirect(request.getContextPath() + addres); // 重定向到文件
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,80 @@
package com.slife.config.cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
/**
* ehcache配置
*
* @author chen
*/
@Configuration
@EnableCaching
public class CacheConfig {
private Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());
@Bean(name = "ehCacheManager")
public EhCacheManager ehCacheManager() {
logger.info("--------------ehCacheManager init---------------");
EhCacheManager cacheManager = new EhCacheManager();
cacheManager.setCacheManagerConfigFile("classpath:cache/ehcache-shiro.xml");
logger.info("--------------ehCacheManager init---------------" + cacheManager);
return cacheManager;
}
@Autowired
private RedisTemplate redisTemplate;
@Bean(name = "slifeRedisCacheManager")
@Primary
public SlifeRedisCacheManager slifeRedisCacheManager() {
logger.info("--------------redis cache init---------------");
SlifeRedisCacheManager slifeRedisCacheManager = new SlifeRedisCacheManager();
slifeRedisCacheManager.setRedisTemplate(redisTemplate);
logger.info("--------------redis cache ---------------" + slifeRedisCacheManager);
return slifeRedisCacheManager;
}
@Bean(name = "redisCacheManager")
@Primary
public RedisCacheManager redisCacheManager() {
logger.info("--------------redis cache init---------------");
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
logger.info("--------------redis cache ---------------" + redisCacheManager);
return redisCacheManager;
}
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int database;
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPassword(password);
redisManager.setPort(port);
redisManager.setDatabase(database);
return redisManager;
}
}
@@ -0,0 +1,82 @@
package com.slife.config.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author chen
*/
public class SlifeRedisCache<K, V> implements Cache<K, V> {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String REDIS_SHIRO_CACHE = "slife-shiro-cache:";
private String cacheKey;
private RedisTemplate<K, V> redisTemplate;
private long globExpire = 30;
@SuppressWarnings("rawtypes")
public SlifeRedisCache(String name, RedisTemplate client) {
this.cacheKey = REDIS_SHIRO_CACHE + name + ":";
this.redisTemplate = client;
}
@Override
public V get(K key) throws CacheException {
redisTemplate.boundValueOps(getCacheKey(key)).expire(globExpire, TimeUnit.MINUTES);
return redisTemplate.boundValueOps(getCacheKey(key)).get();
}
@Override
public V put(K key, V value) throws CacheException {
V old = get(key);
redisTemplate.boundValueOps(getCacheKey(key)).set(value);
return old;
}
@Override
public V remove(K key) throws CacheException {
V old = get(key);
redisTemplate.delete(getCacheKey(key));
return old;
}
@Override
public void clear() throws CacheException {
redisTemplate.delete(keys());
}
@Override
public int size() {
return keys().size();
}
@Override
public Set<K> keys() {
return redisTemplate.keys(getCacheKey("*"));
}
@Override
public Collection<V> values() {
Set<K> set = keys();
List<V> list = new ArrayList<>();
for (K s : set) {
list.add(get(s));
}
return list;
}
private K getCacheKey(Object k) {
return (K) (this.cacheKey + k);
}
}
@@ -0,0 +1,36 @@
package com.slife.config.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
/**
* @author chen
*/
public class SlifeRedisCacheManager implements CacheManager {
private static final Logger logger = LoggerFactory.getLogger(SlifeRedisCacheManager.class);
private RedisTemplate redisTemplate;
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
return new SlifeRedisCache<K, V>(name, redisTemplate);
}
public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
@@ -0,0 +1,24 @@
attach_path: E:/ideaword/moban/slife/attach/
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/slife?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
druid:
validationQuery: SELECT 1
initialSize: 10
minIdle: 10
maxActive: 200
minEvictableIdleTimeMillis: 180000
testOnBorrow: false
testWhileIdle: true
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true
poolPreparedStatements: true
maxOpenPreparedStatements: 100
server:
port: 8081
@@ -0,0 +1,26 @@
attach_path: /slife/attach/
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/slife?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
druid:
validationQuery: SELECT 1
initialSize: 10
minIdle: 10
maxActive: 200
minEvictableIdleTimeMillis: 180000
testOnBorrow: false
testWhileIdle: true
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true
poolPreparedStatements: true
maxOpenPreparedStatements: 100
server:
port: 8081
context-path: /slife