shiro cacheManager 采用redis实现

master
星期八 6 years ago
parent e172074e15
commit fb5f63a9de
  1. 23
      pom.xml
  2. 6
      src/main/java/com/lq/cms/service/SysResourceService.java
  3. 4
      src/main/java/com/lq/cms/web/wechat/WechatRuleController.java
  4. 70
      src/main/java/com/lq/code/cache/RedisShiroCache.java
  5. 23
      src/main/java/com/lq/code/cache/RedisShiroManager.java
  6. 55
      src/main/java/com/lq/code/dto/QueueDto.java
  7. 7
      src/main/java/com/lq/code/executor/processor/InstantiationTracingBeanPostProcessor.java
  8. 25
      src/main/java/com/lq/code/util/BeanUtil.java
  9. 4
      src/main/java/com/lq/code/util/sql/AbstractDbBuiler.java
  10. 76
      src/main/java/com/lq/code/util/sql/MysqlBuilder.java
  11. 7
      src/main/java/com/lq/code/util/sql/OracleBuiler.java
  12. 4
      src/main/resources/dev/redis.properties
  13. 4
      src/main/resources/spring/spring-redis.xml
  14. 28
      src/main/resources/spring/spring-shiro.xml
  15. 20
      src/main/webapp/WEB-INF/views/jsp/index.jsp
  16. 16
      src/main/webapp/WEB-INF/web.xml

@ -173,6 +173,20 @@
<version>${spring.version}</version>
</dependency>
<!-- 处理事务和AOP所需的包 (低于1.7用(@PointCut)切点注解会报错) -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
@ -309,7 +323,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
<version>2.1.6.RELEASE</version>
</dependency>
<!--json包-->
@ -499,6 +513,13 @@
<version>3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.2</version>
</dependency>
</dependencies>

@ -4,8 +4,6 @@ import com.lq.cms.mode.MenusComposite;
import com.lq.cms.vo.SysResourceVo;
import com.lq.code.service.BaseService;
import com.lq.entity.SysResource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@ -18,9 +16,9 @@ public interface SysResourceService extends BaseService<SysResource> {
List<SysResource> findByParentId(long parenId);
//通过用户查找相关的菜单
List<MenusComposite> findMenusListBySysUserId(Long sysUserId, HttpServletRequest request);
List<MenusComposite> findMenusListBySysUserId(Long sysUserId,String contextPath);
//用户拥有admin权限查询全部菜单
List<MenusComposite> findAllMenusList(HttpServletRequest request);
List<MenusComposite> findAllMenusList(String contextPath);
}

@ -54,18 +54,18 @@ public class WechatRuleController {
* @param vo
* @param keywordListStr 关键字集合json字符串
* @param messageListStr 消息集合json字符串
* @param wechatInfoId 微信公众号详情ID
* @return
*/
@ResponseBody
@RequestMapping("/save")
public Object save(WechatRuleVo vo,String keywordListStr,String messageListStr,Long wechatInfoId){
public Object save(WechatRuleVo vo,String keywordListStr,String messageListStr){
AjaxResult ajaxResult = new AjaxResult();
if (StringUtil.isNotNull(keywordListStr)) {
List<WechatKeyword> wechatKeywordList = JSON.parseArray(keywordListStr, WechatKeyword.class);
vo.setWechatKeywordList(wechatKeywordList);
}
wechatRuleService.saveRule(vo);
return ajaxResult;
}

@ -0,0 +1,70 @@
package com.lq.code.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Collection;
import java.util.Set;
/**
* @Author: qi
* @Description:
* @Date: Create in 10:07 AM 2019/6/10
*/
public class RedisShiroCache<K,V> implements Cache<K,V>{
@Autowired
private RedisTemplate<K,V> redisTemplate;
public RedisTemplate<K, V> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public V get(K k) throws CacheException {
return redisTemplate.opsForValue().get(k);
}
@Override
public V put(K k, V v) throws CacheException {
redisTemplate.opsForValue().set(k,v);
return v;
}
@Override
public V remove(K k) throws CacheException {
V v = redisTemplate.opsForValue().get(k);
if (redisTemplate.delete(k)){
return v;
}
return v;
}
@Override
public void clear() throws CacheException {
}
@Override
public int size() {
return 0;
}
@Override
public Set<K> keys() {
return null;
}
@Override
public Collection<V> values() {
return null;
}
}

@ -0,0 +1,23 @@
package com.lq.code.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @Author: qi
* @Description:
* @Date: Create in 10:15 PM 2019/6/8
*/
public class RedisShiroManager implements CacheManager {
@Autowired
private RedisShiroCache redisShiroCache;
@Override
public <K, V> Cache<K, V> getCache(String s) throws CacheException {
return redisShiroCache;
}
}

@ -0,0 +1,55 @@
package com.lq.code.dto;
import com.github.jsonzou.jmockdata.JMockData;
import com.lq.entity.SysUser;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @Author: qi
* @Description:自定义队列
* @Date: Create in 9:23 AM 2019/6/3
*/
public class QueueDto<T> {
private List<T> list;
private int index;
public QueueDto() {
this.list = new ArrayList<>();
}
public QueueDto(int size) {
this.list = new ArrayList<>(size);
}
public void add(T t){
list.add(t);
index++;
}
public synchronized T pop(){
T t = null;
index--;
if (hasNext()) {
t = list.get(index);
}
return t;
}
/**
* 判断是否还有元素存在
* @return
*/
public boolean hasNext(){
boolean result = true;
if (index==0){
result = false;
}
return result;
}
}

@ -41,10 +41,13 @@ public class InstantiationTracingBeanPostProcessor implements ApplicationListene
//需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
//扫描实体类
if (isUpdateDB) {
Set<Class> set = BeanUtil.getClassList(packagePath);
long startTime = System.currentTimeMillis();
Set<Class> set = BeanUtil.getClassSet(packagePath);
AbstractDbBuiler dbBuiler = new MysqlBuilder();
String sql = dbBuiler.automaticUpdateDb(set);
JdbcUtils.createTable(sql);
// JdbcUtils.createTable(sql);
System.out.println("=========实体同步数据结构===========");
System.out.println(System.currentTimeMillis()-startTime);
}
}
}

@ -1,5 +1,6 @@
package com.lq.code.util;
import com.lq.code.dto.QueueDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -161,7 +162,7 @@ public class BeanUtil {
* @param packagePath
* @return
*/
public static Set<Class> getClassList(String packagePath){
public static Set<Class> getClassSet(String packagePath){
Set<Class> set = new HashSet<>();
String separator = File.separator;
@ -185,6 +186,28 @@ public class BeanUtil {
return set;
}
public static QueueDto<Class> getQueueDto(String packagePath){
QueueDto<Class> classQueueDto = new QueueDto<>();
String separator = File.separator;
String filePath = packagePath.replace(".",separator);
String classPath = BeanUtil.class.getResource(FILE_SYMBOL).getPath()+filePath;
File file = new File(classPath);
if (file.exists()){
File[] files = file.listFiles();
try {
for (File classFile:files){
String className = classFile.getName().split("\\.")[0];
Class clazz =Class.forName(packagePath+"."+className);
classQueueDto.add(clazz);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return classQueueDto;
}
public static String getEntityName(Class entityClazz){
String entityPath=entityClazz.getName();
String [] entityNameArray=entityPath.split("\\.");

@ -1,5 +1,7 @@
package com.lq.code.util.sql;
import com.lq.code.dto.QueueDto;
import java.util.Set;
/**
@ -10,6 +12,8 @@ public abstract class AbstractDbBuiler {
abstract public String automaticUpdateDb(Set<Class> classSet);
abstract public String automaticUpdateDbNew(QueueDto<Class> classQueueDto);
/**
*  构建分页sql语句
* @param sql

@ -1,6 +1,7 @@
package com.lq.code.util.sql;
import com.lq.code.annotation.Length;
import com.lq.code.dto.QueueDto;
import com.lq.code.util.BeanUtil;
import com.lq.code.util.jdbc.JdbcUtils;
import com.lq.code.util.jdbc.mode.Column;
@ -8,6 +9,7 @@ import com.lq.code.util.jdbc.mode.Table;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.*;
/**
* Created by qi_liang on 2018/6/2.
@ -31,17 +33,13 @@ public class MysqlBuilder extends AbstractDbBuiler {
public String automaticUpdateDb(Set<Class> classSet) {
StringBuffer sql = new StringBuffer();
//扫描实体类包的实体class
Set<Class> set = classSet;
Map<String, Class> map = new HashMap<>();
Iterator<Class> setIterator = set.iterator();
while (setIterator.hasNext()){
Class clazz = setIterator.next();
Map<String, Class> map = new HashMap<>(classSet.size());
classSet.forEach(clazz->{
map.put(SqlUtil.beanNameToTableName(clazz), clazz);
}
});
List<Table> tableList = JdbcUtils.getAllTable();
//初始化的时候,tableList可能为null
if(tableList!=null) {
if(tableList!=null&&tableList.size()>0) {
Iterator<Table> tableIterator = tableList.iterator();
while (tableIterator.hasNext()) {
Table table = (Table) tableIterator.next();
@ -90,10 +88,68 @@ public class MysqlBuilder extends AbstractDbBuiler {
}
}
}
for (String key : map.keySet()) {
sql.append(this.createTableStr(map.get(key)));
for (Map.Entry<String,Class> entry:map.entrySet()){
sql.append(this.createTableStr(entry.getValue()));
}
return sql.toString();
}
@Override
public String automaticUpdateDbNew(QueueDto<Class> classQueueDto) {
StringBuffer sql = new StringBuffer();
List<Table> tableList = JdbcUtils.getAllTable();
Map<String,Table> tableMap = new HashMap<>(tableList.size());
tableList.forEach((table)->{
tableMap.put(table.getTableName(),table);
});
ExecutorService executorService = Executors.newFixedThreadPool(6);
while (classQueueDto.hasNext()){
executorService.execute(()->{
Class clazz = classQueueDto.pop();
String tableName = SqlUtil.beanNameToTableName(clazz);
//判断表是否存在
if (tableMap.containsKey(tableName)){
List<Field> fieldsList = BeanUtil.getAllField(clazz);
Map<String,Field> clazzMap = new HashMap<>(fieldsList.size());
fieldsList.forEach((field)->{
clazzMap.put(SqlUtil.caseToHump(field.getName()),field);
});
List<Column> columnList = tableMap.get(tableName).getColumns();
Iterator<Column> columnIterator = columnList.iterator();
while (columnIterator.hasNext()) {
Column column = columnIterator.next();
if (clazzMap.containsKey(column.getColumnName())) {
clazzMap.remove(column.getColumnName());
columnIterator.remove();
}
}
columnIterator = columnList.iterator();
while (columnIterator.hasNext()) {
Column column = columnIterator.next();
sql.append("ALTER TABLE " + tableName + " DROP COLUMN " + column.getColumnName() + ";");
}
for (Map.Entry<String,Field> entry:clazzMap.entrySet()){
Field f = entry.getValue();
String column = SqlUtil.caseToHump(f.getName());
String columnType = dataTypeMap.get(f.getGenericType().toString());
String lengthStr = "";
if ("varchar".equals(columnType) || "int".equals(columnType)) {
Length length = f.getAnnotation(Length.class);
if (length != null) {
lengthStr = "(" + length.value() + ")";
} else {
lengthStr = "(50)";
}
}
sql.append("ALTER TABLE " + tableName + " ADD COLUMN " + column + " " + columnType + lengthStr + ";");
}
}else {
sql.append(this.createTableStr(clazz));
}
});
}
return sql.toString();
}

@ -1,5 +1,7 @@
package com.lq.code.util.sql;
import com.lq.code.dto.QueueDto;
import java.util.Set;
/**
@ -13,6 +15,11 @@ public class OracleBuiler extends AbstractDbBuiler {
return null;
}
@Override
public String automaticUpdateDbNew(QueueDto<Class> classQueueDto) {
return null;
}
@Override
public String concatPageSql(String sql, PageInterface pageInterface) {
StringBuffer sb=new StringBuffer("select * from (select t1.*,ROWNUM rm from(");

@ -3,8 +3,8 @@ redis.port=6379
redis.pass=
redis.timeout=-1
redis.maxTotal=30
redis.maxIdle=10
redis.maxTotal=10
redis.maxIdle=5
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.minEvictableIdleTimeMillis=1800000

@ -64,6 +64,10 @@
p:poolConfig-ref="jedisConfig"
/>
<!-- 添加RedisHttpSessionConfiguration用于session共享 -->
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<bean id="redisTempale" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>

@ -18,20 +18,11 @@
<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
<!-- 配置Session DAO的操作处理 -->
<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<!-- 设置session缓存的名字,这个名字可以任意 -->
<property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
<!-- 定义该Session DAO操作中所使用的ID生成器 -->
<property name="sessionIdGenerator" ref="sessionIdGenerator"/>
<!-- session缓冲管理-->
<property name="cacheManager" ref="shiroCacheManager"/>
</bean>
<!-- <bean id="sessionDAO" class="com.lq.code.cache.RedisSessionDao">
<bean id="sessionDAO" class="com.lq.code.cache.RedisSessionDao">
<constructor-arg ref="redisTempale"/>
<constructor-arg value="7200"/>
</bean>
-->
<!-- 配置需要向Cookie中保存数据的配置模版 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<!-- 在Tomcat运行下默认使用的Cookie的名字为JSESSIONID -->
@ -40,9 +31,9 @@
<property name="httpOnly" value="true"/>
<!-- 定义Cookie的过期时间,单位为秒,如果设置为-1表示浏览器关闭,则Cookie消失 -->
<property name="maxAge" value="-1"/>
</bean>
</bean>
<!-- 定义会话管理器的操作 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
@ -138,11 +129,18 @@
<property name="configLocation" value="classpath:ehcache/ehcache-shiro.xml"/>
</bean>
-->
<!-- shiro 缓存管理器-->
<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml"/>
<bean id="shiroCache" class="com.lq.code.cache.RedisShiroCache">
</bean>
<bean id="shiroCacheManager" class="com.lq.code.cache.RedisShiroManager">
</bean>
<!-- shiro 缓存管理器-->
<!-- <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>-->
<!--配置bean 后置处理器:会自动的调用和spring 整合后的各个组件的生命周期方法 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

@ -32,16 +32,18 @@
// doucument.cookie = 'bb=bbbbbb';
$("#btn").click(function () {
alert("测试!");
wx.miniProgram.getEnv(function (res) {
if (res.miniprogram) {
//如果当前是小程序环境
wx.miniProgram.postMessage({
data: {
name: 'name',
age: 12
}
})
wx.miniProgram.navigateTo({
url:'/pages/test/test',
success: function(){
console.log('success')
},
fail: function(){
console.log('fail');
},
complete:function(){
console.log('complete');
}
});
})

@ -32,6 +32,7 @@
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 字符编码设置 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
@ -67,6 +68,21 @@
</filter-mapping>
<!-- 配置 shiro 的Filter end-->
<!-- redis共享session -->
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>/public/*,*.js,*.css,*.jsp,*.swf</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring mvc 核心分发器 -->
<servlet>
<servlet-name>MVC-dispatcher</servlet-name>

Loading…
Cancel
Save