SpringBoot项目集成SpringSession,使用redis实现会话共享.做到可配置.

 

 前提:公司开发产品,对接不同省份,一起开发,有些地方需要实现redis会话共享,有些地方是单机部署.可通过配置是否开启redis实现session共享.

 SpringBoot集成SpringSession实现会话共享:

   主要是通过application.properties里面的spring.session.store-type=none参数配置.none单机版.redis会话共享

  • pom添加依赖

		
			org.springframework.session
			spring-session
		
  • application.properties添加session和redis配置

#session 
#配合为redis表示开启redis会话共享,none单机
spring.session.store-type=none
spring.session.redis.namespace=evidence

#redis配置
spring.data.redis.repositories.enabled=true
spring.redis.database=0
spring.redis.host=
spring.redis.port=6379
spring.redis.pool.max-active=1024
spring.redis.pool.min-idle=10
  • 添加SpringSession的配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieHttpSessionStrategy;
import org.springframework.session.web.http.CookieSerializer;

@Configuration
public class SpringSessionConfig {

	@Bean
	public CookieHttpSessionStrategy cookieHttpSessionStrategy() {
		CookieHttpSessionStrategy strategy = new CookieHttpSessionStrategy();
		strategy.setCookieSerializer(buildCustomerCookieSerializer());
		return strategy;
	}

	private CookieSerializer buildCustomerCookieSerializer() {
		// TODO Auto-generated method stub
		return new CustomerCookieSerializer();
	}

}

 

  • 使用Jackson2JsonRedisSerialize 替换默认序列化 

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.SessionRepository;
import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;


public class ApplicationStartup  implements ApplicationListener {

	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		// TODO Auto-generated method stub
		RedisSerializer serializer = jacksonRedisSerializer();
		RedisOperationsSessionRepository redisOperationsSessionRepository = event.getApplicationContext().getBean(RedisOperationsSessionRepository.class);
	settingRedisOperationsSessionRepository(redisOperationsSessionRepository,serializer);
		RedisTemplate redisTemplate =  (RedisTemplate)event.getApplicationContext().getBean("sessionRedisTemplate");
		settingRedisTemplate(redisTemplate,serializer);

	}

	private void settingRedisOperationsSessionRepository(RedisOperationsSessionRepository redisOperationsSessionRepository,RedisSerializer serializer) {
		redisOperationsSessionRepository.setDefaultSerializer(serializer);
	}

	private void settingRedisTemplate(RedisTemplate redisTemplate,RedisSerializer serializer) {
		redisTemplate.setDefaultSerializer(serializer);
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashValueSerializer(serializer);
		redisTemplate.setValueSerializer(serializer);
		redisTemplate.afterPropertiesSet();
	}

	public Jackson2JsonRedisSerializer jacksonRedisSerializer() {
		// 使用Jackson2JsonRedisSerialize 替换默认序列化
		ObjectMapper objectMapper = new ObjectMapper();
		settingObjectMapper(objectMapper);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
		return jackson2JsonRedisSerializer;
	}

	private void settingObjectMapper(ObjectMapper objectMapper) {
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		objectMapper.setSerializationInclusion(Include.NON_NULL);

	}

} 
  

 

 

  • 启动类添加是否启用redis实现会话共享

import com.iflytek.evidence.utils.ApplicationPropertiesUtils;
import com.iflytek.icourt.fdfs.conn.TrackerConnectionManager;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.TimeZone;

@SpringBootApplication
@EnableTransactionManagement
@EnableAsync
@EnableRetry
@MapperScan("com.xxx.xxx.mapper")
@EnableConfigurationProperties({TrackerConnectionManager.class})
public class EvidenceCheckApplication extends SpringBootServletInitializer {


    public static void main(String[] args) {
        initTimeZone();
        if (isRedisSessionStoreType()) {
            SpringApplication app = new SpringApplication(EvidenceCheckApplication.class);
            app.addListeners(new ApplicationStartup());
            app.run(args);
        } else {
            SpringApplication.run(EvidenceCheckApplication.class, args);
        }
    }


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        initTimeZone();
        if (isRedisSessionStoreType()) {
            builder.listeners(new ApplicationStartup());
        }
        // TODO Auto-generated method stub
        return builder.sources(EvidenceCheckApplication.class);
    }

    public static void initTimeZone() {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
    }


    private static boolean isRedisSessionStoreType() {
        return "redis".equalsIgnoreCase(getSessionStoreType());
    }

    private static String getSessionStoreType() {
        return ApplicationPropertiesUtils.getStrValue("spring.session.store-type");
    }
}

 

你可能感兴趣的:(SpringBoot项目集成SpringSession,使用redis实现会话共享.做到可配置.)