springboot集成redis存储session

4 篇文章 0 订阅
1 篇文章 0 订阅

1.依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
 </dependency>

2.redis配置类

package com.jlh.complete.moudle.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/***
 * @description:
 * @author: Jianglh
 * @date: 2019/11/26 13:43
 */
@Configuration
public class RedisConfig {
    @Autowired
    private MyStringSerializer myStringSerializer;

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();

        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式

        template.setKeySerializer(myStringSerializer);

        // hash的key也采用String的序列化方式

        template.setHashKeySerializer(myStringSerializer);

        // value序列化方式采用jackson

        template.setValueSerializer(jackson2JsonRedisSerializer);

        // hash的value序列化方式采用jackson

        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }
}

3.自定义key序列化类

package com.jlh.complete.moudle.redis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

/***
 * @description:
 * @author: Jianglh
 * @date: 2019/11/26 14:26
 */

@Component
public class MyStringSerializer implements RedisSerializer<String> {
    private final Logger logger = LoggerFactory.getLogger ( this.getClass () );

    @Autowired
    private RedisProperties redisProperties;

    private final Charset charset;

    public MyStringSerializer() {
        this ( Charset.forName ( "UTF8" ) );
    }

    public MyStringSerializer(Charset charset) {
        Assert.notNull ( charset, "Charset must not be null!" );
        this.charset = charset;
    }

    @Override
    public String deserialize(byte[] bytes) {
        String keyPrefix = redisProperties.getKeyPrefix ();
        String saveKey = new String ( bytes, charset );
        int indexOf = saveKey.indexOf ( keyPrefix );
        if (indexOf > 0) {
            logger.info ( "key缺少前缀" );
        } else {
            saveKey = saveKey.substring ( indexOf );
        }
        logger.info ( "saveKey:{}",saveKey);
        return (saveKey.getBytes () == null ? null : saveKey);
    }

    @Override
    public byte[] serialize(String string) {
        String keyPrefix = redisProperties.getKeyPrefix ();
        String key = keyPrefix + string;
        logger.info ( "key:{},getBytes:{}",key, key.getBytes ( charset ));
        return (key == null ? null : key.getBytes ( charset ));
    }
}

4.增加key值命名空间即前缀

package com.jlh.complete.moudle.redis.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/***
 * @description:
 * @author: Jianglh
 * @date: 2019/11/26 14:28
 */
@Data
@Component
@ConfigurationProperties(prefix = "redis")
@PropertySource("classpath:redis.properties")
public class RedisProperties {
   
    /**
     * key前缀
     */
    private String keyPrefix;


}

5.配置文件

文件名 redis.properties
#地址
spring.redis.host=*******
#端口
spring.redis.port=6379
#索引库
spring.redis.database=0
#密码
spring.redis.password=****
#超时时间  300000等于300秒
spring.redis.timeout=300000

#将themilef的默认缓存禁用,热加载生效
#spring.thymeleaf.cache=false
redis.keyPrefix=0000-->

6.单独创建redis.properties文件需在springboot启动类上加配置  还可配置session生存时间

package com.jlh.complete;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
//import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@SpringBootApplication(scanBasePackages = "com.jlh.complete")
@MapperScan("com.jlh.complete.moudle.*.dao")
//启动时使用redis配置文件
@PropertySource(value = {"classpath:redis.properties"})
//启用redis做session存储使用   默认存活时间1800秒
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=60)
public class CompleteApplication {

    public static void main(String[] args) {
        SpringApplication.run(CompleteApplication.class, args);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值