Spring Boot中Redis數(shù)據(jù)庫(kù)的使用實(shí)例
spring boot對(duì)常用的數(shù)據(jù)庫(kù)支持外,對(duì)nosql 數(shù)據(jù)庫(kù)也進(jìn)行了封裝自動(dòng)化。
redis介紹
Redis是目前業(yè)界使用最廣泛的內(nèi)存數(shù)據(jù)存儲(chǔ)。相比memcached,Redis支持更豐富的數(shù)據(jù)結(jié)構(gòu),例如hashes, lists, sets等,同時(shí)支持?jǐn)?shù)據(jù)持久化。除此之外,Redis還提供一些類(lèi)數(shù)據(jù)庫(kù)的特性,比如事務(wù),HA,主從庫(kù)??梢哉f(shuō)Redis兼具了緩存系統(tǒng)和數(shù)據(jù)庫(kù)的一些特性,因此有著豐富的應(yīng)用場(chǎng)景。本文介紹Redis在Spring Boot中兩個(gè)典型的應(yīng)用場(chǎng)景。
如何使用
1、引入 spring-boot-starter-redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
2、添加配置文件
# REDIS (RedisProperties) # Redis數(shù)據(jù)庫(kù)索引(默認(rèn)為0) spring.redis.database=0 # Redis服務(wù)器地址 spring.redis.host=192.168.0.58 # Redis服務(wù)器連接端口 spring.redis.port=6379 # Redis服務(wù)器連接密碼(默認(rèn)為空) spring.redis.password= # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制) spring.redis.pool.max-active=8 # 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制) spring.redis.pool.max-wait=-1 # 連接池中的最大空閑連接 spring.redis.pool.max-idle=8 # 連接池中的最小空閑連接 spring.redis.pool.min-idle=0 # 連接超時(shí)時(shí)間(毫秒) spring.redis.timeout=0
3、添加cache的配置類(lèi)
@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); //設(shè)置緩存過(guò)期時(shí)間 //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、好了,接下來(lái)就可以直接使用了
@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("aa@126.com", "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()); } }
以上都是手動(dòng)使用的方式,如何在查找數(shù)據(jù)庫(kù)的時(shí)候自動(dòng)使用緩存呢,看下面;
4、自動(dòng)根據(jù)方法生成緩存
@RequestMapping("/getUser") @Cacheable(value="user-key") public User getUser() { User user=userRepository.findByUserName("aa"); System.out.println("若下面沒(méi)出現(xiàn)“無(wú)緩存的時(shí)候調(diào)用”字樣且能打印出數(shù)據(jù)表示測(cè)試成功"); return user; }
其中value的值就是緩存到redis中的key
共享Session-spring-session-data-redis
分布式系統(tǒng)中,sessiong共享有很多的解決方案,其中托管到緩存中應(yīng)該是最常用的方案之一,
Spring Session官方說(shuō)明
Spring Session provides an API and implementations for managing a user’s session information.
如何使用
1、引入依賴(lài)
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
2、Session配置:
@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) public class SessionConfig { }
maxInactiveIntervalInSeconds: 設(shè)置Session失效時(shí)間,使用Redis Session之后,原Boot的server.session.timeout屬性不再生效
好了,這樣就配置好了,我們來(lái)測(cè)試一下
3、測(cè)試
添加測(cè)試方法獲取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*'
t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4 t(spring:session:expirations:1472976480000
其中 1472976480000為失效時(shí)間,意思是這個(gè)時(shí)間后session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4 為sessionId,登錄http://localhost:8080/uid 發(fā)現(xiàn)會(huì)一致,就說(shuō)明session 已經(jīng)在redis里面進(jìn)行有效的管理了。
如何在兩臺(tái)或者多臺(tái)共享session
其實(shí)就是按照上面的步驟在另一個(gè)項(xiàng)目中再次配置一次,啟動(dòng)后自動(dòng)就進(jìn)行了session共享。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)一鍵生成表controller,service,mapper文件
這篇文章主要為大家詳細(xì)介紹了如何利用Java語(yǔ)言實(shí)現(xiàn)一鍵生成表controller,service,mapper文件,文中的示例代碼講解詳細(xì),需要的可以收藏一下2023-05-05Idea工具中使用Mapper對(duì)象有紅線(xiàn)的解決方法
mapper對(duì)象在service層有紅線(xiàn),項(xiàng)目可以正常使用,想知道為什么會(huì)出現(xiàn)這種情,接下來(lái)通過(guò)本文給大家介紹下Idea工具中使用Mapper對(duì)象有紅線(xiàn)的問(wèn)題,需要的朋友可以參考下2022-09-09簡(jiǎn)單了解Java編程中對(duì)異常處理的運(yùn)用
這篇文章主要簡(jiǎn)單介紹了Java編程中對(duì)異常處理的運(yùn)用,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09詳解用Spring Boot Admin來(lái)監(jiān)控我們的微服務(wù)
這篇文章主要介紹了用Spring Boot Admin來(lái)監(jiān)控我們的微服務(wù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動(dòng)過(guò)期時(shí)間及自動(dòng)刷新功能
用過(guò)spring cache的朋友應(yīng)該會(huì)知道,Spring Cache默認(rèn)是不支持在@Cacheable上添加過(guò)期時(shí)間的,雖然可以通過(guò)配置緩存容器時(shí)統(tǒng)一指定,本文主要介紹了如何基于spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動(dòng)過(guò)期時(shí)間以及緩存即將到期自動(dòng)刷新,2024-02-02Java實(shí)現(xiàn)模擬機(jī)器人對(duì)話(huà)的示例代碼
本文主要介紹了Java實(shí)現(xiàn)模擬機(jī)器人對(duì)話(huà)的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Spring異常實(shí)現(xiàn)統(tǒng)一處理的方法
這篇文章主要介紹了Spring異常實(shí)現(xiàn)統(tǒng)一處理的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-12-12mybatis和mybatisplus批量插入問(wèn)題示例詳解
最近在處理一個(gè)功能的時(shí)候,需要批量插入數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于mybatis和mybatisplus批量插入問(wèn)題的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹非常詳細(xì),需要的朋友可以參考下2023-04-04