日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

【Springboot学习】SpringBoot集成Shiro前后端分离使用redis做缓存【个人博客搭建】

發布時間:2023/12/29 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Springboot学习】SpringBoot集成Shiro前后端分离使用redis做缓存【个人博客搭建】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

shiro-redis

目錄

  • shiro-redis
  • 下載
    • shiro-core/jedis 版本對比圖
  • 使用前
  • 如何配置?
    • 設置文件
      • Redis 獨立
      • Redis哨兵
      • Redis 集群
    • Spring
      • Redis 獨立
      • Redis哨兵
      • Redis 集群
    • 序列化器 Serializer
    • 可配置選項 Configurable Options
      • Redis管理器
      • RedisSessionDAO
      • CacheManager 緩存管理器
  • 彈簧啟動器 Spring boot starter
    • 如果您還沒有創建自己的`SessionManager`或`SessionsSecurityManager`
    • 如果您已經創建了自己的`SessionManager`或`SessionsSecurityManager`
      • 配置屬性 Configuration Properties
    • Working with `spring-boot-devtools`
  • 如果您發現任何錯誤

alexxiyang / shiro-redis

shiro 只提供 ehcache 和 concurrentHashMap 的支持。這里有一個 shiro 可以使用的 redis 緩存實現。希望它會幫助你!

下載

您可以使用以下 2 種方式之一包含shiro-redis到您的項目中

  • 用于git clone https://github.com/alexxiyang/shiro-redis.git將項目克隆到本地工作區并自行構建 jar 文件
  • 添加maven依賴
<dependency><groupId>org.crazycake</groupId><artifactId>shiro-redis</artifactId><version>3.3.1</version> </dependency>

注意:
3.3.0 錯誤地在java11 中編譯。請使用java8編譯的3.3.1

shiro-core/jedis 版本對比圖

shiro-redisshirojedis
3.2.31.3.22.9.0
3.3.0 (java11)1.6.03.3.0
3.3.1 (java8)1.6.03.3.0

使用前

這是您需要了解的第一件事。Shiro-redis 需要一個 id 字段來標識您在 Redis 中的授權對象。所以請確保你的主類有一個字段,你可以得到這個對象的唯一 id。請通過以下方式設置此 ID 字段名稱cacheManager.principalIdFieldName = <your id field name of principal object>

例如:

如果你這樣創建SimpleAuthenticationInfo:

@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;UserInfo userInfo = new UserInfo();userInfo.setUsername(usernamePasswordToken.getUsername());return new SimpleAuthenticationInfo(userInfo, "123456", getName()); }

那么userInfo對象就是你的主要對象。您需要確保UserInfoRedis 有一個唯一的字段來識別它。以userId為例:

public class UserInfo implements Serializable{private Integer userIdprivate String username;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Integer getUserId() {return this.userId;} }

將 userId 作為 的值cacheManager.principalIdFieldName,如下所示:

cacheManager.principalIdFieldName = userId

如果你使用的是 Spring,配置應該是

<property name="principalIdFieldName" value="userId" />

然后shiro-redis將調用userInfo.getUserId()獲取 id 以保存 Redis 對象。

如何配置?

您可以配置shiro-redisinshiro.ini或 inspring-*.xml

設置文件

下面是 shiro.ini 的配置示例。

Redis 獨立

如果您在獨立模式下運行 Redis

[main] #==================================== # shiro-redis configuration [start] #====================================#=================================== # Redis Manager [start] #===================================# Create redisManager redisManager = org.crazycake.shiro.RedisManager# Redis host. If you don't specify host the default value is 127.0.0.1:6379 redisManager.host = 127.0.0.1:6379#=================================== # Redis Manager [end] #===================================#========================================= # Redis session DAO [start] #=========================================# Create redisSessionDAO redisSessionDAO = org.crazycake.shiro.RedisSessionDAO# Use redisManager as cache manager redisSessionDAO.redisManager = $redisManagersessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManagersessionManager.sessionDAO = $redisSessionDAOsecurityManager.sessionManager = $sessionManager#========================================= # Redis session DAO [end] #=========================================#========================================== # Redis cache manager [start] #==========================================# Create cacheManager cacheManager = org.crazycake.shiro.RedisCacheManager# Principal id field name. The field which you can get unique id to identify this principal. # For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc. # Remember to add getter to this id field. For example, `getId()`, `getUserId()`, `getEmail()`, etc. # Default value is id, that means your principal object must has a method called `getId()` cacheManager.principalIdFieldName = id# Use redisManager as cache manager cacheManager.redisManager = $redisManagersecurityManager.cacheManager = $cacheManager#========================================== # Redis cache manager [end] #==========================================#================================= # shiro-redis configuration [end] #=================================

有關完整的可配置選項列表,請檢查Configurable Options。

這是一個教程項目,讓您了解如何shiro-redis在shiro.ini.

Redis哨兵

如果您使用的是Redis Sentinel,請將redisManager獨立版本的配置替換為以下內容:

#=================================== # Redis Manager [start] #===================================# Create redisManager redisManager = org.crazycake.shiro.RedisSentinelManager# Sentinel host. If you don't specify host the default value is 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 redisManager.host = 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381# Sentinel master name redisManager.masterName = mymaster#=================================== # Redis Manager [end] #===================================

有關完整的可配置選項列表,請檢查Configurable Options。

Redis 集群

如果您使用的是redis集群,請將redisManager獨立版本的配置替換為以下內容:

#=================================== # Redis Manager [start] #===================================# Create redisManager redisManager = org.crazycake.shiro.RedisClusterManager# Redis host and port list redisManager.host = 192.168.21.3:7000,192.168.21.3:7001,192.168.21.3:7002,192.168.21.3:7003,192.168.21.3:7004,192.168.21.3:7005#=================================== # Redis Manager [end] #===================================

有關完整的可配置選項列表,請檢查Configurable Options。

Spring

如果您使用的是 Spring

Redis 獨立

如果您在獨立模式下運行 Redis

<!-- shiro-redis configuration [start] --><!-- Redis Manager [start] --> <bean id="redisManager" class="org.crazycake.shiro.RedisManager"><property name="host" value="127.0.0.1:6379"/> </bean> <!-- Redis Manager [end] --><!-- Redis session DAO [start] --> <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO"><property name="redisManager" ref="redisManager" /> </bean> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"><property name="sessionDAO" ref="redisSessionDAO" /> </bean> <!-- Redis session DAO [end] --><!-- Redis cache manager [start] --> <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager"><property name="redisManager" ref="redisManager" /> </bean> <!-- Redis cache manager [end] --><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="sessionManager" ref="sessionManager" /><property name="cacheManager" ref="cacheManager" /><!-- other configurations --><property name="realm" ref="exampleRealm"/><property name="rememberMeManager.cipherKey" value="kPH+bIxk5D2deZiIxcaaaA==" /> </bean><!-- shiro-redis configuration [end] -->

有關完整的可配置選項列表,請檢查Configurable Options。

這里有一個教程項目,讓你了解如何shiro-redis在spring配置文件中進行配置。

Redis哨兵

如果使用redis sentinel,請將redisManager單機版的配置改為如下:

<!-- shiro-redis configuration [start] --> <!-- shiro redisManager --> <bean id="redisManager" class="org.crazycake.shiro.RedisSentinelManager"><property name="host" value="127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"/><property name="masterName" value="mymaster"/> </bean>

有關完整的可配置選項列表,請檢查Configurable Options。

Redis 集群

如果使用redis集群,請將redisManagerstandalone版本的配置改為如下:

<!-- shiro-redis configuration [start] --> <!-- shiro redisManager --> <bean id="redisManager" class="org.crazycake.shiro.RedisClusterManager"><property name="host" value="192.168.21.3:7000,192.168.21.3:7001,192.168.21.3:7002,192.168.21.3:7003,192.168.21.3:7004,192.168.21.3:7005"/> </bean>

有關完整的可配置選項列表,請檢查Configurable Options。

序列化器 Serializer

由于 redis 只接受byte[],就會出現序列化問題。Shiro-redisStringSerializer用作鍵序列化器和ObjectSerializer值序列化器。你可以使用你自己的自定義序列化器,只要這個自定義序列化器實現org.crazycake.shiro.serializer.RedisSerializer

例如,我們可以像這樣更改 keySerializer 的字符集

# If you want change charset of keySerializer or use your own custom serializer, you need to define serializer first # # cacheManagerKeySerializer = org.crazycake.shiro.serializer.StringSerializer# Supported encodings refer to https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html # UTF-8, UTF-16, UTF-32, ISO-8859-1, GBK, Big5, etc # # cacheManagerKeySerializer.charset = UTF-8# cacheManager.keySerializer = $cacheManagerKeySerializer

您可以使用自定義序列化程序替換這 4 個選項:

  • cacheManager.keySerializer
  • cacheManager.valueSerializer
  • redisSessionDAO.keySerializer
  • redisSessionDAO.valueSerializer

可配置選項 Configurable Options

以下是您可以在shiro-redis配置文件中使用的所有可用選項。

Redis管理器

TitleDefaultDescription
host127.0.0.1:6379Redis 主機。如果您不指定主機,則默認值為127.0.0.1:6379. 如果你在哨兵模式或集群模式下運行 redis,用逗號分隔主機名,如127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
masterNamemymaster僅用于哨兵模式 Redis哨兵模式的主節點
timeout2000Redis 連接超時。jedis 嘗試連接到 redis 服務器超時(以毫秒為單位)
soTimeout2000僅用于哨兵模式或集群模式 jedis嘗試從redis服務器讀取數據的超時時間
maxAttempts3僅用于集群模式 最大嘗試連接到服務器
passwordRedis密碼
database0Redis 數據庫。默認值為 0
jedisPoolConfignew redis.clients.jedis.JedisPoolConfig()JedisPoolConfig. 您可以創建自己的 JedisPoolConfig 實例并根據需要設置屬性 大多數情況下,您不需要設置 jedisPoolConfig 這里是一個示例。 jedisPoolConfig = redis.clients.jedis.JedisPoolConfig jedisPoolConfig.testWhileIdle = false redisManager.jedisPoolConfig = jedisPoolConfig
count100掃描計數。Shiro-redis 使用 Scan 來獲取鍵,因此您可以定義每次迭代返回的元素數量。
jedisPoolnull僅用于哨兵模式或單模式 您可以創建自己的 JedisPool 實例并根據需要設置屬性

RedisSessionDAO

TitleDefaultDescription
redisManager您剛剛在上面配置的RedisManager(必需)
expire-2Redis 緩存鍵/值過期時間。過期時間以秒為單位。 特殊值: -1: no expire -2:與會話超時相同 默認值:-2 注意:確保過期時間長于會話超時。
keyPrefixshiro:session:為會話管理自定義您的 redis 密鑰前綴 注意:請記住在前綴末尾添加冒號。
sessionInMemoryTimeout1000當我們登錄時,doReadSession(sessionId)會被 shiro 調用大約 10 次。所以shiro-redis將Session保存在ThreadLocal中來緩解這個問題。sessionInMemoryTimeout 是 ThreadLocal 中 Session 的到期時間。 大多數情況下,您不需要更改它。
sessionInMemoryEnabledtrue是否在 ThreadLocal 中啟用臨時保存會話
keySerializerorg.crazycake.shiro.serializer.StringSerializer緩存管理器的key serializer 你可以改變key serializer 的實現或者StringSerializer 的編碼。 支持的編碼是指支持的編碼。如UTF-8, UTF-16, UTF-32, ISO-8859-1, GBK, Big5, 等 更多細節請查看Serializer
valueSerializerorg.crazycake.shiro.serializer.ObjectSerializer緩存管理器的值序列化器 您可以更改值序列化器的實現 有關更多詳細信息,請查看Serializer

CacheManager 緩存管理器

TitleDefaultDescription
redisManager您剛剛在上面配置的RedisManager(必需)
principalIdFieldNameid主體 ID 字段名稱。您可以獲得唯一 ID 來標識此主體的字段。 例如,如果您使用 UserInfo 作為 Principal 類,則 id 字段可能id是userId、email、 等。 請記住將 getter 添加到此 id 字段。例如,getId(), getUserId(),getEmail()等。 默認值是id,這意味著您的主體對象必須有一個方法調用getId()
expire1800Redis 緩存鍵/值過期時間。 過期時間以秒為單位。
keyPrefixshiro:cache:自定義您的 redis 鍵前綴以進行緩存管理 注意:請記住在前綴末尾添加冒號。
keySerializerorg.crazycake.shiro.serializer.StringSerializer緩存管理器的key serializer 你可以改變key serializer 的實現或者StringSerializer 的編碼。 支持的編碼是指支持的編碼。如UTF-8, UTF-16, UTF-32, ISO-8859-1, GBK, Big5, 等 更多細節請查看Serializer
valueSerializerorg.crazycake.shiro.serializer.ObjectSerializer緩存管理器的值序列化器 您可以更改值序列化器的實現 有關更多詳細信息,請查看Serializer

彈簧啟動器 Spring boot starter

使用Spring-Boot集成是集成shiro-redis到基于 Spring 的應用程序的最簡單方法。

注意:shiro-redis-spring-boot-starter版本3.2.1基于shiro-spring-boot-web-starter版本1.4.0-RC2

首先shiro-redis在您的應用程序類路徑中包含Spring boot starter 依賴項

<dependency><groupId>org.crazycake</groupId><artifactId>shiro-redis-spring-boot-starter</artifactId><version>3.3.1</version> </dependency>

下一步取決于您是創建了自己的SessionManager還是SessionsSecurityManager.

如果您還沒有創建自己的SessionManager或SessionsSecurityManager

如果您沒有自己的SessionManager或SessionsSecurityManager在您的配置中,shiro-redis-spring-boot-starter將創建RedisSessionDAO并RedisCacheManager為您。然后將它們注入SessionManager并SessionsSecurityManager自動注入。所以,你都準備好了。享受吧!

如果您已經創建了自己的SessionManager或SessionsSecurityManager

如果您創建了自己的SessionManager或SessionsSecurityManager喜歡這樣的:

@Bean public SessionsSecurityManager securityManager(List<Realm> realms) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realms);// other stuff...return securityManager; }

然后注入redisSessionDAO和已經redisCacheManager創建的shiro-redis-spring-boot-starter

@Autowired RedisSessionDAO redisSessionDAO;@Autowired RedisCacheManager redisCacheManager;

將它們注入您自己的SessionManager和SessionsSecurityManager

@Bean public SessionManager sessionManager() {DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();// inject redisSessionDAOsessionManager.setSessionDAO(redisSessionDAO);// other stuff...return sessionManager; }@Bean public SessionsSecurityManager securityManager(List<Realm> realms, SessionManager sessionManager) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realms);//inject sessionManagersecurityManager.setSessionManager(sessionManager);// inject redisCacheManagersecurityManager.setCacheManager(redisCacheManager);// other stuff...return securityManager; }

有關完整示例,請參閱shiro-redis-spring-boot-tutorial

配置屬性 Configuration Properties

以下是您可以在 Spring-boot 啟動器配置中使用的所有可用選項

標題 Title默認 Default說明 Description
shiro-redis.enabledtrue啟用 shiro-redis 的 Spring 模塊
shiro-redis.redis-manager.deploy-modestandaloneRedis 部署模式。選項: standalone, sentinel, ‘集群’
shiro-redis.redis-manager.host127.0.0.1:6379Redis 主機。如果您不指定主機,則默認值為127.0.0.1:6379. 如果你在哨兵模式或集群模式下運行 redis,用逗號分隔主機名,如127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
shiro-redis.redis-manager.master-namemymaster僅用于哨兵模式 Redis哨兵模式的主節點
shiro-redis.redis-manager.timeout2000Redis 連接超時。jedis 嘗試連接到 redis 服務器超時(以毫秒為單位)
shiro-redis.redis-manager.so-timeout2000僅用于哨兵模式或集群模式 jedis嘗試從redis服務器讀取數據的超時時間
shiro-redis.redis-manager.max-attempts3僅用于集群模式 最大嘗試連接到服務器
shiro-redis.redis-manager.passwordRedis密碼
shiro-redis.redis-manager.database0Redis 數據庫。默認值為 0
shiro-redis.redis-manager.count100掃描計數。Shiro-redis 使用 Scan 來獲取鍵,因此您可以定義每次迭代返回的元素數量。
shiro-redis.session-dao.expire-2Redis 緩存鍵/值過期時間。過期時間以秒為單位。 特殊值: -1: no expire -2:與會話超時相同 默認值:-2 注意:確保過期時間長于會話超時。
shiro-redis.session-dao.key-prefixshiro:session:為會話管理自定義您的 redis 密鑰前綴 注意:請記住在前綴末尾添加冒號。
shiro-redis.session-dao.session-in-memory-timeout1000當我們登錄時,doReadSession(sessionId)會被 shiro 調用大約 10 次。所以shiro-redis將Session保存在ThreadLocal中來緩解這個問題。sessionInMemoryTimeout 是 ThreadLocal 中 Session 的到期時間。 大多數情況下,您不需要更改它。
shiro-redis.session-dao.session-in-memory-enabledtrue是否在 ThreadLocal 中啟用臨時保存會話
shiro-redis.cache-manager.principal-id-field-nameid主體 ID 字段名稱。您可以獲得唯一 ID 來標識此主體的字段。 例如,如果您使用 UserInfo 作為 Principal 類,則 id 字段可能id是userId、email、 等。 請記住將 getter 添加到此 id 字段。例如,getId(), getUserId(),getEmail()等。 默認值是id,這意味著您的主體對象必須有一個方法調用getId()
shiro-redis.cache-manager.expire1800Redis 緩存鍵/值過期時間。 過期時間以秒為單位。
shiro-redis.cache-manager.key-prefixshiro:cache:自定義您的 redis 鍵前綴以進行緩存管理 注意:請記住在前綴末尾添加冒號。

Working with spring-boot-devtools

如果您使用shiro-redis與spring-boot-devtools. 請將此行添加到resources/META-INF/spring-devtools.properties(如果沒有此文件,則創建它):

restart.include.shiro-redis=/shiro-[\\w-\\.]+jar

如果您發現任何錯誤

歡迎留言

如果您在學習這篇文章之前對Shiro不了解或者掌握程度較低,建議先閱讀博主我這篇文章

【Springboot學習】Shiro快速入門及與SpringBoot集成

如果您覺得學有余力,歡迎繼續閱讀如下文章

【Java全棧】Java全棧學習路線及項目全資料總結【JavaSE+Web基礎+大前端進階+SSM+微服務+Linux+JavaEE】

可愛的人給一個三連吧

總結

以上是生活随笔為你收集整理的【Springboot学习】SpringBoot集成Shiro前后端分离使用redis做缓存【个人博客搭建】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。