springboot整合redis存放session

y进入maven依赖:

<!--spring boot 与redis应用基本环境配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>
        <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

创建SessionConfig

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

//这个类用配置redis服务器的连接
//maxInactiveIntervalInSeconds为SpringSession的过期时间(单位:秒)


@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800) public class SessionConfig { // 冒号后的值为没有配置文件时,制动装载的默认值 @Value("${redis.hostname:localhost}") String HostName; @Value("${redis.port:6379}") int Port; @Bean public JedisConnectionFactory connectionFactory() { JedisConnectionFactory connection = new JedisConnectionFactory(); connection.setPort(Port); connection.setHostName(HostName); return connection; } }

初始化Session

public class SessionInitializer extends AbstractHttpSessionApplicationInitializer{
    public SessionInitializer() {
        super(SessionConfig.class);
    }
}

控制器层代码

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SessionController {

    @Value("${server.port}")
    private String PORT;

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

    @RequestMapping("/index")
    public String index() {
        return "index:" + PORT;
    }

   // @methodDesc: 功能描述:(往session存放值)
    
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request, String sessionKey, String sessionValue) {
        HttpSession session = request.getSession(true);
        session.setAttribute(sessionKey, sessionValue);
        return "success,port:" + PORT;
    }

   // @methodDesc: 功能描述:(从Session获取值)
    
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request, String sessionKey) {
        HttpSession session =null;
        try {
         session = request.getSession(false);
        } catch (Exception e) {
          e.printStackTrace();
        }
        String value=null;
        if(session!=null){
            value = (String) session.getAttribute(sessionKey);
        }
        return "sessionValue:" + value + ",port:" + PORT;
    }

}

 配置文件

#redis配置
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
#Redis密码
spring.redis.password=redis密码
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
#springboot内置tomcat的端口设置
server.port=8080

redis也可以这样配置:

@Configuration
@EnableCaching//开启缓存注解
//maxInactiveIntervalInSeconds:session的统一过期时间,默认是1800秒过期,这里测试修改为60秒
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60)//注解,开启redis集中session管理
public class RedisConfig {
    // 以下redisTemplate自由根据场景选择
    //默认的String-String
    //    @Bean
    public RedisTemplate RedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }

    @Bean
    public RedisTemplate<String, Object> RedisTemplate2(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        //GenericJackson2JsonRedisSerializer方便反序列化,redis中也方便查看json
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
    @Bean
    public RedisTemplate<Object, Object> RedisTemplate3(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        template.setValueSerializer(serializer);
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }
    /**
     * redis作为缓存
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object>  redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        // 多个缓存的名称,目前只定义了一个
        rcm.setCacheNames(Arrays.asList("user"));
        //设置缓存过期时间(秒)
        rcm.setDefaultExpiration(60);
        return rcm;
    }

    /**
     * 在springboot中使用spring-session的时候,
     * 在不同的域名下面需要配置cookie主域否则session共享不生效
     * @return
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
        //cookie名字
        defaultCookieSerializer.setCookieName("sessionId");
        //不同子域时设置
        //defaultCookieSerializer.setDomainName("xxx.com");
        //设置各web应用返回的cookiePath一致
        defaultCookieSerializer.setCookiePath("/");
        return defaultCookieSerializer;
    }
}

集群配置:

 spring:  
   redis:  
     cluster:  
       nodes:  
        - Centos6701:6379  
        - Centos6701:6380
        - Centos6702:6380
        - Centos6702:6379 
        - Centos6703:6379 
        - Centos6703:6380

 

高并发解决方案

业务数据库  -》 数据水平分割(分区分表分库)、读写分离

业务应用 -》 逻辑代码优化(算法优化)、公共数据缓存

应用服务器 -》 反向静态代理、配置优化、负载均衡(apache分发,多tomcat实例)

系统环境 -》 JVM调优

页面优化 -》 减少页面连接数、页面尺寸瘦身

1、动态资源和静态资源分离;

2、CDN;

3、负载均衡;

4、分布式缓存;

5、数据库读写分离或数据切分(垂直或水平);

6、服务分布式部署。

 

posted @ 2019-02-20 13:03  菩提树下的丁春秋  阅读(5899)  评论(0编辑  收藏  举报