redis应用

一、依赖包

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-redis</artifactId>
   <version>1.8.9.RELEASE</version>
</dependency>
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.9.0</version>
</dependency>

二、redis配置文件

1)java配置文件

package top.ibase4j.core.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import top.ibase4j.core.support.cache.RedisHelper;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.PropertiesUtil;

@Configuration
public class JedisConfig {
    public JedisConfig() {
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(PropertiesUtil.getInt("redis.minIdle").intValue());
        config.setMaxIdle(PropertiesUtil.getInt("redis.maxIdle").intValue());
        config.setMaxTotal(PropertiesUtil.getInt("redis.maxTotal").intValue());
        config.setMaxWaitMillis((long)PropertiesUtil.getInt("redis.maxWaitMillis").intValue());
        config.setTestOnBorrow(Boolean.valueOf(PropertiesUtil.getString("redis.testOnBorrow")).booleanValue());
        return config;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        String nodes = PropertiesUtil.getString("redis.cluster.nodes");
        JedisConnectionFactory jedisConnectionFactory;
        if (StringUtils.isNotBlank(nodes)) {
            List<String> list = InstanceUtil.newArrayList(nodes.split(","));
            RedisClusterConfiguration configuration = new RedisClusterConfiguration(list);
            configuration.setMaxRedirects(PropertiesUtil.getInt("redis.cluster.max-redirects").intValue());
            jedisConnectionFactory = new JedisConnectionFactory(configuration, jedisPoolConfig);
            jedisConnectionFactory.setPassword(PropertiesUtil.getString("redis.password"));
        } else {
            jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
            jedisConnectionFactory.setHostName(PropertiesUtil.getString("redis.host"));
            jedisConnectionFactory.setPort(PropertiesUtil.getInt("redis.port").intValue());
            jedisConnectionFactory.setPassword(PropertiesUtil.getString("redis.password"));
        }

        jedisConnectionFactory.setTimeout(PropertiesUtil.getInt("redis.timeout").intValue());
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<Serializable, Serializable> redisTemplate = new RedisTemplate();
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericFastJsonRedisSerializer valueSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setEnableTransactionSupport((new Boolean(PropertiesUtil.getString("redis.enableTransaction"))).booleanValue());
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }

    @Bean
    @Qualifier("redisTemplate")
    public RedisHelper redisHelper(RedisTemplate<Serializable, Serializable> redisTemplate) {
        RedisHelper redisHelper = new RedisHelper();
        redisHelper.setRedisTemplate(redisTemplate);
        return redisHelper;
    }

    @Bean
    @Qualifier("redisTemplate")
    public CacheManager redisCacheManager(RedisTemplate<Serializable, Serializable> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setTransactionAware(true);
        cacheManager.setDefaultExpiration((long)PropertiesUtil.getInt("redis.expiration", 10));
        return cacheManager;
    }
}

2)xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
   xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   <!-- jedis 配置 -->
   <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
      <!--最小空闲数 -->
      <property name="minIdle" value="${redis.minIdle}" />
      <!--最大空闲数 -->
      <property name="maxIdle" value="${redis.maxIdle}" />
      <!--最大连接数 -->
      <property name="maxTotal" value="${redis.maxTotal}" />
      <!--最大建立连接等待时间 -->
      <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
      <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 -->
      <property name="testOnBorrow" value="${redis.testOnBorrow}" />
   </bean>
   <!-- redisCluster配置 -->
   <bean id="redisProperty"
      class="org.springframework.core.io.support.ResourcePropertySource"
      c:name="redis.properties" c:resource="classpath:config/system.properties" />
   <bean id="redisClusterConfiguration"
      class="org.springframework.data.redis.connection.RedisClusterConfiguration">
      <constructor-arg name="propertySource" ref="redisProperty" />
   </bean>
   <!-- redis服务器中心 -->
   <bean id="jedisConnectionFactory" class="top.ibase4j.core.support.cache.jedis.ConnectionFactory"
      c:cluster-config-ref="redisClusterConfiguration" c:pool-config-ref="jedisPoolConfig"
      p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.password}"
      p:pool-config-ref="jedisPoolConfig" p:timeout="${redis.timeout}" />
   <!-- 缓存序列化方式 -->
   <bean id="keySerializer"
      class="org.springframework.data.redis.serializer.StringRedisSerializer" />
   <bean id="valueSerializer"
      class="com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer" />
   <!-- 缓存 -->
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
      <property name="connectionFactory" ref="jedisConnectionFactory" />
      <property name="enableTransactionSupport" value="true" />
      <property name="keySerializer" ref="keySerializer" />
      <property name="valueSerializer" ref="valueSerializer" />
      <property name="hashKeySerializer" ref="keySerializer" />
      <property name="hashValueSerializer" ref="valueSerializer" />
   </bean>
   <!-- 缓存管理 -->
   <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
      <constructor-arg index="0" ref="redisTemplate" />
      <property name="transactionAware" value="true" />
      <property name="defaultExpiration" value="${redis.expiration}" />
   </bean>
</beans>

system.properties

redis.host=127.0.0.1
redis.port=6379
redis.password=123
#最小空闲数
redis.minIdle=2
#最大空闲数
redis.maxIdle=10
#最大连接数
redis.maxTotal=1000
#最大建立连接等待时间  
redis.maxWaitMillis=3000
#客户端超时时间单位是毫秒
redis.timeout=120000
#明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个  
redis.testOnBorrow=true
redis.expiration=600
#rediscluster
spring.redis.cluster.nodes=
#spring.redis.cluster.nodes=127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
spring.redis.cluster.max-redirects=3
#rediscluster
redis.master=
redis.slave=

import java.lang.reflect.Field;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

public class ConnectionFactory extends JedisConnectionFactory {
    private Logger logger = LogManager.getLogger();
    private RedisClusterConfiguration clusterConfig;

    public ConnectionFactory(RedisClusterConfiguration clusterConfig, JedisPoolConfig poolConfig) {
        super(poolConfig);
        this.clusterConfig = clusterConfig;
    }

    public void afterPropertiesSet() {
        if (this.clusterConfig != null && this.clusterConfig.getClusterNodes() != null && !this.clusterConfig.getClusterNodes().isEmpty()) {
            try {
                Field clusterConfigField = JedisConnectionFactory.class.getDeclaredField("clusterConfig");
                clusterConfigField.setAccessible(true);
                clusterConfigField.set(this, this.clusterConfig);
            } catch (Exception var2) {
                this.logger.error("", var2);
            }
        }

        super.afterPropertiesSet();
    }
}

三、session 应用


package top.ibase4j.core.support.cache.shiro;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.PropertiesUtil;
import top.ibase4j.core.util.SerializeUtil;

public class RedisSessionDAO extends AbstractSessionDAO {
    private static final int EXPIRE_TIME = 600;
    @Autowired
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    public RedisSessionDAO() {
    }

    private RedisConnection getRedisConnection() {
        return this.redisTemplate.getConnectionFactory().getConnection();
    }

    public void update(Session session) throws UnknownSessionException {
        this.saveSession(session);
    }

    public void delete(Session session) {
        if (session != null) {
            Serializable id = session.getId();
            if (id != null) {
                RedisConnection redisConnection = this.getRedisConnection();

                try {
                    redisConnection.del(new byte[][]{this.buildRedisSessionKey(id)});
                } finally {
                    redisConnection.close();
                }
            }
        }

    }

    public Collection<Session> getActiveSessions() {
        List<Session> list = InstanceUtil.newArrayList();
        RedisConnection redisConnection = this.getRedisConnection();

        try {
            Set<byte[]> set = redisConnection.keys("S:iBase4J:SHIRO-SESSION:*".getBytes());
            Iterator var4 = set.iterator();

            while(var4.hasNext()) {
                byte[] key = (byte[])var4.next();
                list.add(SerializeUtil.deserialize(redisConnection.get(key), SimpleSession.class));
            }
        } finally {
            redisConnection.close();
        }

        return list;
    }

    public void delete(Serializable sessionId) {
        if (sessionId != null) {
            byte[] sessionKey = this.buildRedisSessionKey(sessionId);
            RedisConnection redisConnection = this.getRedisConnection();

            try {
                redisConnection.del(new byte[][]{sessionKey});
            } finally {
                redisConnection.close();
            }
        }

    }

    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        this.saveSession(session);
        return sessionId;
    }

    protected Session doReadSession(Serializable sessionId) {
        byte[] sessionKey = this.buildRedisSessionKey(sessionId);
        RedisConnection redisConnection = this.getRedisConnection();

        Session var6;
        try {
            byte[] value = redisConnection.get(sessionKey);
            Session session;
            if (value == null) {
                session = null;
                return session;
            }

            session = (Session)SerializeUtil.deserialize(value, SimpleSession.class);
            var6 = session;
        } finally {
            redisConnection.close();
        }

        return var6;
    }

    private void saveSession(Session session) {
        if (session != null && session.getId() != null) {
            byte[] sessionKey = this.buildRedisSessionKey(session.getId());
            int sessionTimeOut = PropertiesUtil.getInt("session.maxInactiveInterval", 600);
            byte[] value = SerializeUtil.serialize(session);
            RedisConnection redisConnection = this.getRedisConnection();

            try {
                redisConnection.set(sessionKey, value, Expiration.seconds((long)sessionTimeOut), SetOption.UPSERT);
            } finally {
                redisConnection.close();
            }

        } else {
            throw new UnknownSessionException("session is empty");
        }
    }

    private byte[] buildRedisSessionKey(Serializable sessionId) {
        return ("S:iBase4J:SHIRO-SESSION:" + sessionId).getBytes();
    }
}

四、与@Cacheable等注解引用

package org.ibase4j.service;

import java.util.List;
import java.util.Map;

import org.ibase4j.mapper.SysAuthorizeMapper;
import org.ibase4j.mapper.SysRoleMenuMapper;
import org.ibase4j.mapper.SysUserMenuMapper;
import org.ibase4j.mapper.SysUserRoleMapper;
import org.ibase4j.model.SysDic;
import org.ibase4j.model.SysMenu;
import org.ibase4j.model.SysRoleMenu;
import org.ibase4j.model.SysUserMenu;
import org.ibase4j.model.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

import top.ibase4j.core.Constants;
import top.ibase4j.core.base.BaseService;
import top.ibase4j.core.util.InstanceUtil;

/**
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:19:19
 */
@Service
@CacheConfig(cacheNames = "sysAuthorize")
public class SysAuthorizeService extends BaseService<SysMenu> {
   @Autowired
   private SysUserMenuMapper sysUserMenuMapper;
   @Autowired
   private SysUserRoleMapper sysUserRoleMapper;
   @Autowired
   private SysRoleMenuMapper sysRoleMenuMapper;
   @Autowired
   private SysAuthorizeMapper sysAuthorizeMapper;
   @Autowired
   private SysMenuService sysMenuService;
   @Autowired
   private SysDicService sysDicService;

   public List<String> queryMenuIdsByUserId(Long userId) {
      List<String> resultList = InstanceUtil.newArrayList();
      List<Long> list = sysUserMenuMapper.queryMenuIdsByUserId(userId);
      for (Long id : list) {
         resultList.add(id.toString());
      }
      return resultList;
   }

   @Transactional
   @CacheEvict(value = { Constants.CACHE_NAMESPACE + "menuPermission", Constants.CACHE_NAMESPACE + "sysPermission",
         Constants.CACHE_NAMESPACE + "userPermission" }, allEntries = true)
   public void updateUserMenu(List<SysUserMenu> sysUserMenus) {
      Long userId = null;
      for (SysUserMenu sysUserMenu : sysUserMenus) {
         if (sysUserMenu != null && sysUserMenu.getUserId() != null && "read".equals(sysUserMenu.getPermission())) {
            userId = sysUserMenu.getUserId();
         }
      }
      if (userId != null) {
         sysAuthorizeMapper.deleteUserMenu(userId, "read");
      }
      for (SysUserMenu sysUserMenu : sysUserMenus) {
         if (sysUserMenu != null && sysUserMenu.getUserId() != null && sysUserMenu.getMenuId() != null
               && "read".equals(sysUserMenu.getPermission())) {
            sysUserMenuMapper.insert(sysUserMenu);
         }
      }
   }

   @Cacheable(Constants.CACHE_NAMESPACE + "userPermission")
   public List<String> queryUserPermission(Long userId) {
      return sysUserMenuMapper.queryPermission(userId);
   }

}

package top.ibase4j.core.config;

import com.alibaba.fastjson.JSON;
import java.lang.reflect.Method;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    String prefix = "iBase4J:M:";

    public RedisCacheConfig() {
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder(RedisCacheConfig.this.prefix);
                CacheConfig cacheConfig = (CacheConfig)o.getClass().getAnnotation(CacheConfig.class);
                Cacheable cacheable = (Cacheable)method.getAnnotation(Cacheable.class);
                CachePut cachePut = (CachePut)method.getAnnotation(CachePut.class);
                CacheEvict cacheEvict = (CacheEvict)method.getAnnotation(CacheEvict.class);
                String[] cacheNames;
                if (cacheable != null) {
                    cacheNames = cacheable.value();
                    if (ArrayUtils.isNotEmpty(cacheNames)) {
                        sb.append(cacheNames[0]);
                    }
                } else if (cachePut != null) {
                    cacheNames = cachePut.value();
                    if (ArrayUtils.isNotEmpty(cacheNames)) {
                        sb.append(cacheNames[0]);
                    }
                } else if (cacheEvict != null) {
                    cacheNames = cacheEvict.value();
                    if (ArrayUtils.isNotEmpty(cacheNames)) {
                        sb.append(cacheNames[0]);
                    }
                }

                if (cacheConfig != null && sb.toString().equals(RedisCacheConfig.this.prefix)) {
                    cacheNames = cacheConfig.cacheNames();
                    if (ArrayUtils.isNotEmpty(cacheNames)) {
                        sb.append(cacheNames[0]);
                    }
                }

                if (sb.toString().equals(RedisCacheConfig.this.prefix)) {
                    sb.append(o.getClass().getName()).append(".").append(method.getName());
                }

                sb.append(":");
                if (objects != null) {
                    Object[] var13 = objects;
                    int var10 = objects.length;

                    for(int var11 = 0; var11 < var10; ++var11) {
                        Object object = var13[var11];
                        sb.append(JSON.toJSONString(object));
                    }
                }

                return sb.toString();
            }
        };
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值