使用Redis实现Session共享

Maven依赖

<!-- Shiro核心包 -->
	<dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-core</artifactId>
		<version>1.2.3</version>
	</dependency>
	<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.2</version>
        </dependency>
 
<!-- redis -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.5.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.6.2.RELEASE</version>
    </dependency>
 

redis.properties

#访问地址
redis.host=192.168.1.12
#访问端口
redis.port=6379
#注意,如果没有password,此处不设置值,但这一项要保留
redis.password=123456

#最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.maxIdle=300
#最小空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.minIdle=8
#连接池的最大数据库连接数。设为0表示无限制
redis.maxActive=600
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">

        <!-- 配置文件加载 -->
        <context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties"/>

        <cache:annotation-driven cache-manager="cacheManager"/>

        <!-- jedis 配置 -->
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <property name="maxIdle" value="${redis.maxIdle}" />
            <property name="minIdle" value="${redis.minIdle}" />
            <property name="maxWaitMillis" value="${redis.maxWait}" />
            <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        </bean>
        <!-- redis服务器中心 -->
         <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
             <property name="poolConfig" ref="poolConfig" />
            <property name="port" value="${redis.port}" />
            <property name="hostName" value="${redis.host}" />
            <property name="password" value="${redis.password}" />
            <property name="timeout" value="-1"/>
         </bean>
         <!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="jedisConnectionFactory" />
            <property name="keySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
            </property>
            <property name="valueSerializer">
                <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
            </property>
            <property name="hashKeySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
            </property>
            <property name="hashValueSerializer">
                <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
            </property>
        </bean>

        <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
            <property name="caches">
                <set>
                    <!-- 这里可以配置多个redis -->
                    <bean class="util.RedisCache">
                        <property name="redisTemplate" ref="redisTemplate" />
                        <property name="name" value="content"/>
                        <!-- name对应的名称要在类或方法的注解中使用 -->
                    </bean>
                </set>
            </property>
        </bean>

</beans>

JedisUtil

@Component
public class JedisUtil {
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;
 
    private JedisConnection getJedis(){
        return jedisConnectionFactory.getConnection();
    }
 
    public byte[] set(byte[] key, byte[] value) {
        JedisConnection jedis = getJedis();
        try {
            jedis.set(key,value);
            return value;
        } finally {
            jedis.close();
        }
    }
 
    public void expire(byte[] key, int i) {
        JedisConnection jedis = getJedis();
        try {
            jedis.expire(key,i);
        } finally {
            jedis.close();
        }
    }
 
    public byte[] get(byte[] key) {
        JedisConnection jedis = getJedis();
        try {
            return jedis.get(key);
        } finally {
            jedis.close();
        }
    }
 
    public void del(byte[] key) {
        JedisConnection jedis = getJedis();
        try {
            jedis.del(key);
        } finally {
            jedis.close();
        }
    }
 
    public Set<byte[]> keys(String shiro_session_prefix) {
        JedisConnection jedis = getJedis();
        try {
            return jedis.keys((shiro_session_prefix + "*").getBytes());
        } finally {
            jedis.close();
        }
    }
}

RedisSessionDao

public class RedisSessionDao extends AbstractSessionDAO {

    @Autowired
    private JedisUtil jedisUtil;

    private final String shiro_session_prefix = "shiro-session:";

    private byte[] getKey(String key){
        return (shiro_session_prefix + key).getBytes();
    }

    private void saveSession(Session session){
        if(session != null && session.getId()!=null){
            byte[] key = getKey(session.getId().toString());
            byte[] value = SerializationUtils.serialize(session);
            jedisUtil.set(key,value);
            jedisUtil.expire(key,600);
        }
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionID = generateSessionId(session);
        assignSessionId(session,sessionID);
        saveSession(session);
        return sessionID;
    }

    @Override
    protected Session doReadSession(Serializable sessionID) {
        if(sessionID == null){
            return null;
        }
        byte[] key = getKey(sessionID.toString());
        byte[] value = jedisUtil.get(key);
        return (Session)SerializationUtils.deserialize(value);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        saveSession(session);
    }

    @Override
    public void delete(Session session) {
        if(session == null && session.getId() != null){
            return;
        }
        byte[] key = getKey(session.getId().toString());
        jedisUtil.del(key);

    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<byte[]> keys = jedisUtil.keys(shiro_session_prefix);
        Set<Session> sessions = new HashSet<>();
        if(CollectionUtils.isEmpty(keys)){
            return sessions;
        }
        for(byte[] key:keys){
            Session session = (Session)SerializationUtils.deserialize(jedisUtil.get(key));
            sessions.add(session);
        }
        return sessions;
    }
}

CustomSessionManager

public class CustomSessionManager extends DefaultWebSessionManager {
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;
        if (sessionKey instanceof WebSessionKey) {
            request = ((WebSessionKey)sessionKey).getServletRequest();
        }
        if(request != null && sessionId != null){
            Session session = (Session)request.getAttribute(sessionId.toString());
            if(session != null){
                return session;
            }
        }
        Session session = super.retrieveSession(sessionKey);
        if(request != null && sessionId != null){
            request.setAttribute(sessionId.toString(),session);
        }
        return session;
    }
}

spring-shiro.xml

    <!-- redisSessionDao -->
<bean id="redisSessionDao" class="com.xinjianqiao.mian.session.RedisSessionDao"/>

    <!-- Session Manager -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.CustomSessionManager">
        <property name="sessionDAO" ref="redisSessionDao"/>
</bean>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要使用Redis实现Spring Boot应用程序的会话共享,您需要执行以下步骤: 1. 添加Redis依赖项 在您的Spring Boot项目中添加spring-boot-starter-data-redis依赖项,这将为您提供Redis客户端和Spring Session依赖项。 2. 配置Redis 在application.properties文件中添加Redis配置,包括Redis服务器的主机名、端口和密码。 3. 启用Spring Session 在Spring Boot应用程序中启用Spring Session,您需要将@EnabaleRedisHttpSession注释添加到Spring Boot主应用程序类上。 4. 配置会话超时 您可以在application.properties文件中设置会话超时时间,例如:spring.session.timeout=30m。 5. 测试 最后,您可以测试您的Spring Boot应用程序是否正在使用Redis进行会话共享,通过多个实例运行应用程序,并在每个实例中访问同一URL并查看结果是否相同。 通过这些步骤,您应该能够在Spring Boot应用程序中使用Redis进行会话共享。 ### 回答2: 在Spring Boot中使用Redis实现session共享可以通过以下步骤实现: 1. 首先,确保在pom.xml文件中添加以下依赖项以在Spring Boot中使用Redis: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties文件中配置Redis连接信息: ```properties spring.redis.host=your-redis-host spring.redis.port=your-redis-port spring.redis.password=your-redis-password ``` 3. 创建一个配置类(如RedisConfig.java),用于配置与Redis的连接以及序列化的设置: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400) // 设置session的有效时间,单位为秒 public class RedisConfig { @Bean public RedisSerializer<Object> redisSerializer() { // 使用JSON序列化器,存储到Redis中的Session以JSON格式保存,方便阅读 return new GenericJackson2JsonRedisSerializer(); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置key和value的序列化器 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(redisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(redisSerializer()); return template; } } ``` 4. 在需要使用session的地方注入`HttpSession`,并使用它来获取、设置和删除session中的属性: ```java import javax.servlet.http.HttpSession; // 注入HttpSession @Autowired private HttpSession session; // 获取session中的属性 Object attributeValue = session.getAttribute("attributeName"); // 设置session中的属性 session.setAttribute("attributeName", attributeValue); // 删除session中的属性 session.removeAttribute("attributeName"); ``` 这样,通过以上步骤,就可以在Spring Boot中使用Redis实现session共享了。注意,由于Redis是内存数据库,需要设置session的有效时间以避免占用过多的内存资源。 ### 回答3: 使用Spring Boot实现Session共享的方法有两种:使用Spring Session使用RedisTemplate。 第一种方法是使用Spring Session实现Session共享。Spring Session是一个用于在分布式环境下管理Session的Spring项目,它提供了一种基于Spring的Session管理解决方案。要使用Spring Session,需要在pom.xml文件中添加相关依赖,然后在Spring Boot配置类中加上@EnableRedisHttpSession注解,配置Redis连接信息。这样,Spring Session会将Session信息存储到Redis中,实现Session共享。 第二种方法是使用RedisTemplate来实现Session共享RedisTemplate是Spring Data Redis提供的一个用于操作Redis的模板类,可以方便地进行Redis的读写操作。要使用RedisTemplate实现Session共享,首先需要在pom.xml文件中添加相关依赖,然后在Spring Boot配置类中创建一个RedisConnectionFactory实例,并将其注入到RedisTemplate中。通过RedisTemplate,可以将Session信息存储到Redis中,并实现Session共享。 无论是使用Spring Session还是使用RedisTemplate,都需要在Spring Boot配置文件中配置Redis连接信息,包括Redis服务器的IP地址、端口号和密码(如果有)。此外,还可以配置Redis的连接池参数,以提高性能和并发能力。 总结起来,要使用Spring Boot实现RedisSession共享,可以使用Spring SessionRedisTemplate两种方式。通过配置相关依赖和连接信息,将Session信息存储到Redis中,实现Session共享。这样,在分布式环境下,不同的应用实例之间就能够共享Session,并实现会话的跨应用访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值