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、服務分布式部署。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM