springmvc框架下使用spring-session-data-redis集成redis实现session共享

1、安装redis 具体过程不再讲

2、配置redis

  • bind  127.0.0.1 192.168.1.100  #指定redis绑定的主机地址
  • port 6379 #指定访问redis服务端的端口
  • timeout 1800 #指定客户端连接redis服务器时,当闲置的时间为多少(如1800秒)时,关闭连接。 这个很重要 如果不设置的话,redis连接数会越来越大,直到最大值后报异常
  • tcp-keepalive 300 #redis服务端主动向空闲的客户端发起ack请求,以判断连接是否有效
  • (默认情况下timeout和tcp-keepalive均为0,这种情况下,当服务器和客户端网络不稳定时,导致tcp连接中断,这时redis的client将会一直存在而不会被关闭,直到用尽所有的连接数。)
  • daemonize yes # 默认情况下 redis 不是作为守护进程运行的,如果你想让它在后台运行就设置为yes
  • requirepass good.byb #密码
  • notify-keyspace-events "KEA" #很重要!!!  事件通知  ,当session超期时会自动向客户端发送通知,然后需要在代码中接收时做相应的处理

3、spring配置 maven配置需要引入的包

<jedis.version>2.9.0</jedis.version>
<spring-data-redis.version>1.7.2.RELEASE</spring-data-redis.version>
<spring-session-data-redis.version>1.3.5.RELEASE</spring-session-data-redis.version>

4、web.xml 配置监听

<!--spring session redis监听 -->
<filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

5、新建RedisConstants  全局常量 存储redis用户信息

 

public class RedisConstants {
    //登录用户信息放入redis 试用与用户唯一登录
    public static String REDIS_USER_LOGIN_MAP = "REDIS_USER_LOGIN_MAP";



}

6、配置redisService层服务

package com.xx.service.redis.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

 
@Service("redisService")
public class RedisServiceImpl {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 批量保存list列表 如果存在则先清空,再插入
     *
     * @param key
     * @param value
     */
    public void delAndSaveList(String key, List value) {
        try {
            ListOperations<String, Object> opsForList = redisTemplate.opsForList();
            while (opsForList.size(key) > 0) {
                redisTemplate.opsForList().leftPop(key);
            }
            opsForList.rightPushAll(key, value);
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    /**
     * 插入map对象
     *
     * @param key
     * @param value
     */
    public void saveMap(String key, Map value) {
        try {
            redisTemplate.opsForHash().putAll(key, value);
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    /**
     * 获取map对象
     *
     * @param key
     * @return
     */
    public Map getMap(String key) {
        try {
            return redisTemplate.opsForHash().entries(key);
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    /**
     * 删除map对象
     *
     * @param key
     */
    public void delMap(String key) {
        try {
            redisTemplate.opsForHash().delete(key);
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    /**
     * 删除map中某些值
     *
     * @param key
     * @param hashKeys
     */
    public void delKeyMap(String key, String... hashKeys) {
        try {
            redisTemplate.opsForHash().delete(key, hashKeys);
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    /**
     * @param key
     * @param value
     * @param expireSecond
     */
    public void saveStringValue(String key, String value, Long expireSecond) {
        if (existsKey(key)) {
            delKey(key);
        }
        redisTemplate.opsForValue().set(key, value, expireSecond, TimeUnit.MINUTES);
    }


    /**
     * @param key
     * @return
     */
    public boolean existsKey(final String key) {
        return (Boolean) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.exists(key.getBytes());
            }
        });

    }

    /**
     * @param keys
     */
    public long delKey(final String... keys) {
        return (Long) redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                long result = 0;
                for (int i = 0; i < keys.length; i++) {
                    result = connection.del(keys[i].getBytes());
                }
                return result;
            }
        });
    }

}

7、配置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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- redis 相关配置 -->
    <bean id="poolConfig" 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.maxWait}"/>
        <property name="testOnReturn" value="${redis.testOnReturn}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        <property name="testWhileIdle" value="true"/>
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />



    </bean>

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}"
          p:port="${redis.port}"
          p:password="${redis.password}"
          p:database="${redis.dbIndex}"
          p:pool-config-ref="poolConfig"
          p:usePool="true"
    />

    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
          p:connection-factory-ref="jedisConnectionFactory">
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connection-factory-ref="jedisConnectionFactory"
          p:defaultSerializer-ref="genericJackson2JsonRedisSerializer"
          p:keySerializer-ref="stringRedisSerializer"
          p:hashKeySerializer-ref="stringRedisSerializer"
          p:valueSerializer-ref="genericJackson2JsonRedisSerializer"
          p:hashValueSerializer-ref="genericJackson2JsonRedisSerializer"
          p:enableTransactionSupport="true"
    />

    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>


    <bean id="genericJackson2JsonRedisSerializer"
          class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>

    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplate"/>
        <property name="defaultExpiration" value="${redis.expiration}"/>
    </bean>

    <bean id="redisSessionListener" class="com.hongwan.itms.web.listener.RedisSessionListener"/>


    <bean id="redisHttpSessionConfiguration"
          class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
        <!-- maxInactiveIntervalInSeconds 属性是session的过期时间, 单位秒   半小时 = 30分钟 = 30*60 = 1800S-->
        <property name="maxInactiveIntervalInSeconds" value="1800"/>
        <property name="redisNamespace" value="xx"/>
        <property name="configureRedisAction" value="NO_OP"/>
        <property name="httpSessionListeners">
            <list>
                <ref bean="redisSessionListener"/>
            </list>
        </property>
    </bean>
</beans>

8、redis本地配置文件

redis.host=192.168.1.100
redis.port=6379
redis.password=good.byb
redis.dbIndex=0
redis.timeout=5000

redis.expiration=30000
redis.minIdle=100
redis.maxIdle=300
redis.maxTotal=300
redis.maxWait=10000
redis.testOnBorrow=true
redis.testOnReturn=true

redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000

配置完成后在applicationContext.xml中 引入config文件

 <context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties"/>

并引入spring-redis.xml文件

<import resource="applicationContext-redis.xml"/>

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值