1. 程式人生 > >Spring Boot系列(三):Spring Boot中Redis的使用

Spring Boot系列(三):Spring Boot中Redis的使用

spring boot對常用的資料庫支援外,對nosql 資料庫也進行了封裝自動化。

redis介紹

Redis是目前業界使用最廣泛的記憶體資料儲存。相比memcached,Redis支援更豐富的資料結構,例如hashes, lists, sets等,同時支援資料持久化。除此之外,Redis還提供一些類資料庫的特性,比如事務,HA,主從庫。可以說Redis兼具了快取系統和資料庫的一些特性,因此有著豐富的應用場景。本文介紹Redis在Spring Boot中兩個典型的應用場景。

如何使用

1、引入 spring-boot-starter-redis

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

2、新增配置檔案

# REDIS (RedisProperties)
# Redis資料庫索引預設為0
spring.redis.database=0  
# Redis伺服器地址
spring.redis.host=192.168.0.58
# Redis伺服器連線埠
spring.redis
.port=6379 # Redis伺服器連線密碼預設為空 spring.redis.password= # 連線池最大連線數使用負值表示沒有限制 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

3、新增cache的配置類

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
	
	@Bean
	public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //設定快取過期時間
        //rcm.setDefaultExpiration(60);//秒
        return rcm;
    }
    
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(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);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

3、好了,接下來就可以直接使用了

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class TestRedis {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
	@Autowired
	private RedisTemplate redisTemplate;

    @Test
    public void test() throws Exception {
        stringRedisTemplate.opsForValue().set("aaa", "111");
        Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
    }
    
    @Test
    public void testObj() throws Exception {
        User user=new User("[email protected]", "aa", "aa123456", "aa","123");
        ValueOperations<String, User> operations=redisTemplate.opsForValue();
        operations.set("com.neox", user);
        operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
        Thread.sleep(1000);
        //redisTemplate.delete("com.neo.f");
        boolean exists=redisTemplate.hasKey("com.neo.f");
        if(exists){
        	System.out.println("exists is true");
        }else{
        	System.out.println("exists is false");
        }
       // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
    }
}

以上都是手動使用的方式,如何在查詢資料庫的時候自動使用快取呢,看下面;

4、自動根據方法生成快取

@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
    User user=userRepository.findByUserName("aa");
    System.out.println("若下面沒出現“無快取的時候呼叫”字樣且能打印出資料表示測試成功");  
    return user;
}

其中value的值就是快取到redis中的key

共享Session-spring-session-data-redis

分散式系統中,sessiong共享有很多的解決方案,其中託管到快取中應該是最常用的方案之一,

  • Spring Session官方說明

Spring Session provides an API and implementations for managing a user’s session information.

  • 如何使用

1、引入依賴

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

2、Session配置:

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}
maxInactiveIntervalInSeconds: 設定Session失效時間,使用Redis Session之後,原Boot的server.session.timeout屬性不再生效

好了,這樣就配置好了,我們來測試一下

3、測試

新增測試方法獲取sessionid

@RequestMapping("/uid")
    String uid(HttpSession session) {
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }
        session.setAttribute("uid", uid);
        return session.getId();
    }

登入redis 輸入 keys '*sessions*' xml t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4 t(spring:session:expirations:1472976480000 其中 1472976480000為失效時間,意思是這個時間後session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4 為sessionId,登入localhost:8080/uid 發現會一致,就說明session 已經在redis裡面進行有效的管理了。

  • 如何在兩臺或者多臺中共享session

其實就是按照上面的步驟在另一個專案中再次配置一次,啟動後自動就進行了session共享。

參考

往期回顧

相關推薦

Spring Boot系列()Spring BootRedis的使用

spring boot對常用的資料庫支援外,對nosql 資料庫也進行了封裝自動化。 redis介紹 Redis是目前業界使用最廣泛的記憶體資料儲存。相比memcached,Redis支援更豐富的資料結構,例如hashes, lists, sets等,同時支援資料持久

spring boot 系列之一spring boot 入門

最近在學習spring boot,感覺確實很好用,開發環境搭建和部署確實省去了很多不必須要的重複勞動。 接下來就讓我們一起來複習下。 一、什麼是spring boot ? spring boot是幹嘛的?   Spring Boot是由Pivotal團隊提供的全新框架,

Windows下USB磁碟開發系列列舉系統U盤、並獲取其裝置資訊

前面我們介紹了列舉系統中的U盤碟符(見《Windows下USB磁碟開發系列一:列舉系統中U盤的碟符》)、以及獲取USB裝置的資訊(見《Windows下USB磁碟開發系列二:列舉系統中所有USB裝置》)。有個時候我們不僅僅需要獲取U盤碟符(路徑),而且需要獲取該U盤的硬體資訊,比如廠商、friendl

呼叫鏈系列解讀UAVStack的呼叫鏈技術

本專題前幾篇文章主要從架構層面介紹瞭如何實現分散式呼叫追蹤系統。這篇文章我們不談架構,就其中的一項關鍵技術實現進行深入探討:如何從超文字傳輸協議(HTTP)中獲取request和response的body和header。 在Java中,HTTP協議的請求/響應模型是由Servlet規範+Servlet容

u-boot學習()u-boot原始碼分析

前面兩節已經知道,u-boot其實就是一個大的微控制器程式,它負責啟動核心,主要包括硬體方面的一些初始化。下面就以u-boot-1.2.0為例對u-boot原始碼進行詳細的分析。 u-boot的啟動分為兩個階段,第一階段的程式碼就是上一節所說的連結檔案裡的第一個檔案start.S檔案,它是由組合

springboot()Spring bootRedis的使用

red implement getc factory pro acc 系統 val fault spring boot對常用的數據庫支持外,對nosql 數據庫也進行了封裝自動化。 redis介紹 Redis是目前業界使用最廣泛的內存數據存儲。相比memcached,Red

spring boot 系列spring boot 整合JdbcTemplate

closed com context boot pin pan url wired ace 前面兩篇文章我們講了兩件事情: 通過一個簡單實例進行spring boot 入門 修改spring boot 默認的服務端口號和默認context path 這篇文章我們來看下怎

Spring Boot()Spring bootRedis的使用

spring boot對常用的資料庫支援外,對nosql 資料庫也進行了封裝自動化。 redis介紹 Redis是目前業界使用最廣泛的記憶體資料儲存。相比memcached,Redis支援更豐富的資料結構,例如hashes, lists, sets等,同時支援資料持久化。

Spring Boot 2.0()Spring Boot 開源軟件都有哪些?

Spring Boot 開源 2016年 Spring Boot 還沒有被廣泛使用,在網上查找相關開源軟件的時候沒有發現幾個,到了現在經過2年的發展,很多互聯網公司已經將 Spring Boot 搬上了生產,而使用 Spring Boot 的開源軟件在 Github/碼雲 上面已有不少,這篇文章就給大

Spring Boot 系統之Spring Boot 整合JdbcTemplate

前面兩篇文章我們講了兩件事情: 通過一個簡單例項進行Spring Boot 入門 修改Spring Boot 預設的服務埠號和預設context path 這篇文章我們來看下怎麼通過JdbcTemplate進行資料的持久化。 一、程式碼實現 1、修改pom.xml檔案

Spring Boot 2.0()Spring Boot 開源軟體都有哪些?

2016年 Spring Boot 還沒有被廣泛使用,在網上查詢相關開源軟體的時候沒有發現幾個,到了現在經過2年的發展,很多網際網路公司已經將 Spring Boot 搬上了生產,而使用 Spring Boot 的開源軟體在 Github/碼雲 上面已有不少,這篇文章就給大家介紹一下 Github/碼雲 上面

Spring Boot入門一在Eclipse使用Spring boot

新建的專案目錄大概如下 整體目錄結構和Spring專案一樣,只不過Spring boot的配置檔案遷移到了application.yml(或者application.propertis)。專案的入口為BootTestApplication.java的main函式入口。 在maven配置的pom.xml裡

Spring Boot系列():Spring Boot轉化為json資料格式

Spring Boot為我們良好的提供了我們需要的資料,將資料轉化為json格式,然後返回, 下面請看springboot轉化為json的方式; 第一種方式: SpringBoot框架預設的方式; 步驟: * 1.編寫實體類student; package com.gmm

Spring Boot(十一)Spring BootMongoDB的使用

Spring Boot(十一):Spring Boot中MongoDB的使用 mongodb是最早熱門非關係資料庫的之一,使用也比較普遍,一般會用做離線資料分析來使用,放到內網的居多。由於很多公司使用了雲服務,伺服器預設都開放了外網地址,導致前一陣子大批 MongoDB 因配置漏洞被攻擊,資料被刪,引起了人

Spring-boot系列(6)整合fastjson訊息檢視配置

通過fashjson訊息檢視配置可以控制json返回的情況,例如:資料該欄位為空,返回前端值預設是null,可以使用WriteNullListAsEmpty 改為”“。 springboot整合 在原來專案上增加 依賴 <!--引入fastj

Spring Boot入門()使用Scheduled註解實現定時任務

發布 configure code tps enables err except rup .com 在程序開發的過程中,經常會使用到定時任務來實現一些功能,比如: 系統依賴於外部系統的非核心數據,可以定時同步(每天同步一次) 系統內部一些非核心數據的統計計算,可以定時計算

Spring Boot2 系列教程(五)Spring Boot的 yaml 配置

搞 Spring Boot 的小夥伴都知道,Spring Boot 中的配置檔案有兩種格式,properties 或者 yaml,一般情況下,兩者可以隨意使用,選擇自己順手的就行了,那麼這兩者完全一樣嗎?肯定不是啦!本文就來和大夥重點介紹下 yaml 配置,最後再來看看 yaml 和 properties 配

Spring Boot2 系列教程(八)Spring Boot 配置 Https

https 現在已經越來越普及了,特別是做一些小程式或者公眾號開發的時候,https 基本上都是剛需了。 不過一個 https 證書還是挺費錢的,個人開發者可以在各個雲服務提供商那裡申請一個免費的證書。我印象中有效期一年,可以申請 20 個。 今天要和大家聊的是在 Spring Boot 專案中,如何開啟 h

Spring Boot)——Spring Boot資料訪問

一、簡介 對於資料訪問層,無論是SQL還是NOSQL,Spring Boot預設採用整合Spring Data的方式進行統一處理,新增大量自動配置,遮蔽了很多設定。引入各種xxxTemplate,xxxRepository來簡化我們對資料訪問層的操作。對我們來說只需要進行簡單的設定即

spring-shiro()-- spring boot + mybatis +shrio+spring mvc

前面對shiro記性了一些邏輯的操作,和具體的程式碼片段的操作,現在將我寫的一個小的案例,總結一下。總結完明天就上班了。 本案例使用的是spring boot + spring mvc +mybatis 專案的結構 首先對pom檔案進行操作 <?xml version="