[会话共享实现]Shiro+Session+Redis+Nginx[CAS参考版代码]

本文介绍了如何使用SpringBoot、Shiro、Redis和Nginx来实现博客系统的会话共享。详细步骤包括集成Redis、配置application.properties、自定义RedisSessionDao和RedisCache,以及配置Nginx进行负载均衡。在调试过程中,通过解决服务器挂掉后仍负载请求的问题,成功实现了会话在多个服务器间的共享。
摘要由CSDN通过智能技术生成

使用springboot+shiro+session+redis+nginx实现博客系统的会话共享

集成Redis

先集成单机版的Redis(后续修改为集群)

配置application.properties

#cache指定缓存类型
spring.cache.type=REDIS

#data-redis
spring.redis.database=15
spring.redis.host=192.168.**.**
spring.redis.password=
spring.redis.port=6379
spring.redis.timeout=2000
spring.redis.jedis.pool.max-active=8 
spring.redis.jedis.pool.max-idle=8 
spring.redis.jedis.pool.max-wait=-1 
spring.redis.jedis.pool.min-idle=0 
#spring.redis.sentinel.master=mymaster
#spring.redis.sentinel.nodes=192.168.210.**\:26379
redis.proxyIpDBNum=15

#设置的session和授权等信息的过期时间
#session share   unit hours(设置成分钟方便测试)
session.timeout=3
#cacheTimeOut unit hours
cache.timeout=12

Application开启缓存

@SpringBootApplication
@EnableCaching //开启缓存
public class OneserviceManagerApplication {
    public static void main(String[] args) {
        SpringApplication.run(OneserviceManagerApplication.class, args);
    }
}

编写RedisConfig.java配置类

主要作用是对象序列化

	package com.ch.oneservice.manager.config.redis;
	 
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.cache.annotation.CachingConfigurerSupport;
	import org.springframework.context.annotation.Bean;
	import org.springframework.context.annotation.Configuration;
	import org.springframework.data.redis.connection.RedisConnectionFactory;
	import org.springframework.data.redis.core.RedisTemplate;
	import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
	import org.springframework.data.redis.serializer.StringRedisSerializer;
	 
	@Configuration
	public class RedisConfig extends CachingConfigurerSupport {
	 
	    @Autowired
	    private RedisConnectionFactory redisConnectionFactory;
	 
	    /**
	     * 获取RedisTemplate对象,处理Redis数据,并且进行最佳序列化
	     * @return
	     */
	    @Bean(name="redisTemplate")
	    public RedisTemplate<String, Object> redisTemplate() {
	        RedisTemplate<String, Object> template = new RedisTemplate<>();
	        //手动序列化
	        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
	        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
	        template.setKeySerializer(stringRedisSerializer);
	        template.setValueSerializer(jdkSerializationRedisSerializer);
	        template.setHashKeySerializer(stringRedisSerializer);
	        template.setHashValueSerializer(jdkSerializationRedisSerializer);
	        //连接Redis
	        //jedisConnectionFactory.setDatabase(6);
	        template.setConnectionFactory(redisConnectionFactory);
	        template.afterPropertiesSet();
	        return template;
	    } 
	}

Redis做shiro的session共享

RedisSessionDao的自定义实现

(session的缓存处理)

	package com.ch.evaluation.auth.shiro.cas;
	
	import com.ch.evaluation.common.util.PropertityUtil;
	import org.apache.shiro.session.Session;
	import org.apache.shiro.session.UnknownSessionException;
	import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
	import org.slf4j.Logger;
	import org.slf4j.LoggerFactory;
	import org.springframework.dao.DataAccessException;
	import org.springframework.data.redis.connection.RedisConnection;
	import org.springframework.data.redis.core.RedisCallback;
	import org.springframework.data.redis.core.RedisTemplate;
	
	import java.io.Serializable;
	import java.util.Collection;
	import java.util.HashSet;
	import java.util.Set;
	import java.util.concurrent.TimeUnit;
	
	/**
	 * @description:SessionDao自定义实现
	 * @author: xia hua
	 * @date: 2018年10月19日
	 * @modify by wangwei  at 2018-10-19
	 * 将redis中存储的session时间单位改成毫秒
	 */
	@SuppressWarnings("all")
	public class RedisSessionDao extends AbstractSessionDAO {
	    private final String PREFIX="shiro_redis_session:";
	    private static Logger logger = LoggerFactory.getLogger(RedisSessionDao.class);
	    private RedisTemplate redisTpl;
	
	    @Override
	    public void update(Session session) throws UnknownSessionException {
	        if (session==null || session.getId() == null){
	            logger.error("redis update session error:session or session id is null");
	            return;
	        }
	
	        try {
	            redisTpl.opsForValue().set(PREFIX+session.getId().toString(), session, PropertityUtil.getPropertity("session.timeout"), TimeUnit.HOURS);
	        } catch (Exception e) {
	            // TODO: handle exception
	            logger.error(e.getMessage(), e);
	            throw new UnknownSessionException(e);
	        }
	    }
	
	    @Override
	    public void delete(Session session) {
	        // TODO Auto-generated method stub
	        if (session==null || session.getId() == null){
	            logger.error("redis delete session error:session or session id is null");
	            return;
	        }
	        try {
	            redisTpl.delete(PREFIX+session.getId().toString());
	        } catch (Exception e) {
	            // TODO: handle exception
	            logger.error(e.getMessage(), e);
	        }
	    }
	
	    @Override
	    public Collection<Session> getActiveSessions() {
	        // TODO Auto-generated method stub
	        return (Collection<Session>) redisTpl.execute(new RedisCallback<Collection<Session>>() {
	            @Override
	            public Collection<Session&g
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值