SpringBoot(二十四)整合Redis
快取現在幾乎是所有中大型網站都在用的必殺技,合理的利用快取不僅能夠提升網站訪問速度,還能大大降低資料庫的壓力。Redis提供了鍵過期功能,也提供了靈活的鍵淘汰策略,所以,現在Redis用在快取的場合非常多。
之前有兩篇博文(centos安裝Redis 和 Redis五大資料型別的常用操作 ),分別介紹了Redis的安裝和Redis的常用操作。今天主要介紹介紹springboot整合Redis。
v 應用場景
現在公司做的專案都偏重論壇/社群/社交類產品,所以對Redis的實用場景主要集中在排行榜,最新/最熱內容,Redis提供的有序集合資料類構能實現各種複雜的排行榜應用。還有點贊、踩、關注/被關注、共同好友等是社交網站的基本功能,社交網站的訪問量通常來說比較大,而且傳統的關係資料庫型別不適合儲存這種型別的資料,Redis提供的雜湊、集合等資料結構能很方便的的實現這些功能。
還有很多應用場景,比如分散式會話和分散式鎖(分散式鎖感興趣的可以看我之前的一篇文章 《Java分散式鎖,搞懂分散式鎖實現看這篇文章就對了》 )等等,總之越來越廣泛。
v 搭建Redis
1.1. 引入Redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--<dependency>--> <!--<groupId>redis.clients</groupId>--> <!--<artifactId>jedis</artifactId>--> <!--<version>2.9.0</version>--> <!--</dependency>-->
注意redis.clients是我本地除錯測試用的,可以忽略。
1.2. 新增RedisCacheConfig
package com.demo.Redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import java.util.concurrent.CountDownLatch; /** * Created by toutou on 2019/1/20. */ @Configuration @EnableCaching public class RedisCacheConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } public class Receiver { private CountDownLatch latch; @Autowired public Receiver(CountDownLatch latch) { this.latch = latch; } public void receiveMessage(String message) { latch.countDown(); } } }
可以按需新增,也可以按需忽略。
1.3. 新增Redis配置,修改application.properties
# ----- Redis -------- # # REDIS (RedisProperties) # Redis資料庫索引(預設為0) spring.redis.database=0 # Redis伺服器地址 spring.redis.host=10.168.11.129 # 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=5000
1.4. 新增Service
package com.demo.service; import com.demo.pojo.UserDetails; /** * Created by toutou on 2018/10/15. */ public interface UserService { UserDetails getUserDetailsByUid(int uid); String getUserNameById(Integer uid); void setUserNameById(Integer uid, String userName); }
UserServiceImpl
package com.demo.service; import com.demo.dao.UserDetailsMapper; import com.demo.dao.UserPositionMapper; import com.demo.pojo.UserDetails; import com.demo.pojo.UserPosition; import com.google.common.base.Strings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.List; /** * Created by toutou on 2018/10/15. */ @Service public class UserServiceImpl implements UserService{ @Autowired UserDetailsMapper userDetailsMapper; @Autowired UserPositionMapper userPositionMapper; @Autowired StringRedisTemplate template; static final String KEY_USER_INFO__NAME = "com_demo_user_info_007_%s"; public String getUserNameById(Integer uid){ String userName = "未知使用者"; try { userName = template.opsForValue().get(String.format(KEY_USER_INFO__NAME, uid)); if (Strings.isNullOrEmpty(userName)) { // Redis中沒有就讀資料庫 UserDetails userDetails = getUserDetailsByUid(uid); if (userDetails != null && !Strings.isNullOrEmpty(userDetails.getCity())) { userName = userDetails.getCity(); } } }catch(Exception e){ System.out.println(e.toString()); } return userName; } public void setUserNameById(Integer uid, String userName){ template.opsForValue().set(String.format(KEY_USER_INFO__NAME, uid), userName); } public UserDetails getUserDetailsByUid(int uid){ return userDetailsMapper.getUserDetailsByUid(uid); } }
1.5. 新增RedisController
package com.demo.controller; import com.demo.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import redis.clients.jedis.Jedis; /** * Created by toutou on 2019/1/20. */ @RestController @Slf4j public class RedisController { @Autowired UserService userService; @RequestMapping(value = "/getusernamebyid") public String getUserNameById(Integer uid) { return userService.getUserNameById(uid); } @RequestMapping(value = "/setusernamebyid") public String setUserNameById(Integer uid, String uname) { userService.setUserNameById(uid, uname); return "設定成功"; } @RequestMapping(value = "/jedistest") public String jedisTest(){ // 建立一個jedis物件 Jedis jedis = new Jedis("ip", 6379); // 直接呼叫jedis物件的方法,方法名稱和redis的命令一致 jedis.set("key1", "test01"); String key1 = jedis.get("key1"); System.out.println(key1 + " " + key1); // 關閉jedis jedis.close(); return key1; } }
注意jedisTest是我本地除錯測試用的,可以忽略。
v Redis測試效果
v 原始碼地址
https://github.com/toutouge/javademo/tree/master/hellospringboot
作者: 請叫我頭頭哥
出處: http://www.cnblogs.com/toutou/
關於作者:專注於基礎平臺的專案開發。如有問題或建議,請多多賜教!
版權宣告:本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連結。
特此宣告:所有評論和私信都會在第一時間回覆。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信我
聲援博主:如果您覺得文章對您有幫助,可以點選文章右下角一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!