基於spring的redis配置(單機和叢集模式)
這篇文章帶給大家的內容是關於基於spring的redis配置(單機和集群模式) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
所需的jar套件:spring版本:4.3.6.RELEASE,jedis版本:2.9.0,spring-data-redis:1.8.0.RELEASE;如果使用jackson序列化的話還額外需要:jackson -annotations和jackson-databind套件
spring集成redis单机版: 1.配置RedisTemplate <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <property name="defaultSerializer" ref="stringRedisSerializer"/> <property name="keySerializer" ref="stringRedisSerializer"/> <property name="valueSerializer" ref="valueSerializer"/> </bean> 2.配置connectionFactory <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <!-- 配置ip --> <property name="hostName" value="${redis.host}"/> <!-- 配置port --> <property name="port" value="${redis.port}"/> <!-- 是否使用连接池--> <property name="usePool" value="${redis.usePool}"/> <!-- 配置redis连接池--> <property name="poolConfig" ref="poolConfig"/> </bean> 3.配置连接池 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!--最大空闲实例数--> <property name="maxIdle" value="${redis.maxIdle}" /> <!--最大活跃实例数--> <property name="maxTotal" value="${redis.maxTotal}" /> <!--创建实例时最长等待时间--> <property name="maxWaitMillis" value="${redis.maxWaitMillis}" /> <!--创建实例时是否验证--> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> spring集成redis集群 1.配置RedisTemplate步骤与单机版一致 2.配置connectionFactory <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <!-- 配置redis连接池--> <constructor-arg ref="poolConfig"></constructor-arg> <!-- 配置redis集群--> <constructor-arg ref="clusterConfig"></constructor-arg> <!-- 是否使用连接池--> <property name="usePool" value="${redis.usePool}"/> </bean> 3.配置连接池步骤与单机版一致 4.配置redis集群 <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration"> <property name="maxRedirects" value="3"></property> <property name="clusterNodes"> <set> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg value="${redis.host1}"></constructor-arg> <constructor-arg value="${redis.port1}"></constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg value="${redis.host2}"></constructor-arg> <constructor-arg value="${redis.port2}"></constructor-arg> </bean> ...... </set> </property> </bean> 或者 <bean name="propertySource" class="org.springframework.core.io.support.ResourcePropertySource"> <constructor-arg name="location" value="classpath:properties/spring-redis-cluster.properties" /> </bean> <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration"> <constructor-arg name="propertySource" ref="propertySource"/> </bean>
序列化配置簡述:
1.stringRedisSerializer:由于redis的key是String类型所以一般使用StringRedisSerializer 2.valueSerializer:对于redis的value序列化,spring-data-redis提供了许多序列化类,这里建议使用Jackson2JsonRedisSerializer,默认为JdkSerializationRedisSerializer 3.JdkSerializationRedisSerializer: 使用JDK提供的序列化功能。 优点是反序列化时不需要提供类型信息(class),但缺点是序列化后的结果非常庞大,是JSON格式的5倍左右,这样就会消耗redis服务器的大量内存。 4.Jackson2JsonRedisSerializer:使用Jackson库将对象序列化为JSON字符串。优点是速度快,序列化后的字符串短小精悍。但缺点也非常致命,那就是此类的构造函数中有一个类型参数,必须提供要序列化对象的类型信息(.class对象)。
使用spring註解式來配置redis,這裡只配置叢集範例
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { //spring3支持注解方式获取value 在application里配置配置文件路径即可获取 @Value("${spring.redis.cluster.nodes}") private String clusterNodes; @Value("${spring.redis.cluster.timeout}") private Long timeout; @Value("${spring.redis.cluster.max-redirects}") private int redirects; @Value("${redis.maxIdle}") private int maxIdle; @Value("${redis.maxTotal}") private int maxTotal; @Value("${redis.maxWaitMillis}") private long maxWaitMillis; @Value("${redis.testOnBorrow}") private boolean testOnBorrow; /** * 选择redis作为默认缓存工具 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); //cacheManager.setDefaultExpiration(60); //Map<String,Long> expiresMap=new HashMap<>(); //expiresMap.put("redisCache",5L); //cacheManager.setExpires(expiresMap); return cacheManager; } @Bean public RedisClusterConfiguration redisClusterConfiguration(){ Map<String, Object> source = new HashMap<>(); source.put("spring.redis.cluster.nodes", clusterNodes); source.put("spring.redis.cluster.timeout", timeout); source.put("spring.redis.cluster.max-redirects", redirects); return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source)); } @Bean public JedisConnectionFactory redisConnectionFactory(RedisClusterConfiguration configuration){ JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(maxIdle); poolConfig.setMaxTotal(maxTotal); poolConfig.setMaxWaitMillis(maxWaitMillis); poolConfig.setTestOnBorrow(testOnBorrow); return new JedisConnectionFactory(configuration,poolConfig); } /** * retemplate相关配置 * @param factory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 //om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } }
注意事項:
1.採用註解式設定redis或使用@Configuration需要在設定檔中指定掃描什麼哪些包下的設定文件,當然如果是springboot那當我沒說過這句話...
<context:component-scan base-package="com.*"/>
2.spring3支援註解方式取得Value,但是需要在載入的設定檔設定檔路徑即可,具體值自己指定吧...
<value>classpath:properties/spring-redis-cluster.properties</value>
3.由於我們公司原有的框架採用的是spring2.5.6, 而對於spring2 和spring2 主要區別(當然是我自己覺得啊)是把各模組分成了不同的jar,而對於使用spring-data-redis模板化處理redis的話,單機情況下spring2.5.6和spring4不會衝突,而如果使用集群模式需要配置redis集群的時候就會出現jar包衝突,這個時候就看要如何取決了,可以直接使用jedisCluster來連接redis集群(不過很多方法都需要自己去寫),也可以把spring2.5.6替換成高版本的spring4,只是框架替換需要注意的事情更多了啊(我們公司的直接全部替換沒啥毛病好吧,O(∩_∩)O哈哈~),至於重寫JedisConnectionFactory和RedisClusterConfiguration我還沒去嘗試,這個可以作為後續補充吧...
4.順便說句,spring4不在支援ibatis了,如果你需要用spring4,又需要連接ibatis的話,最粗暴的方式是把spring-orm包換成spring3版本,其他的jar還是4版本即可。 (當然我這邊直接替換是沒啥問題,但同3一樣可能有潛在問題啊,所以說嘛,公司有時候還是需要更新換代下吧...)
#以上是基於spring的redis配置(單機和叢集模式)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

Redis集群模式通過分片將Redis實例部署到多個服務器,提高可擴展性和可用性。搭建步驟如下:創建奇數個Redis實例,端口不同;創建3個sentinel實例,監控Redis實例並進行故障轉移;配置sentinel配置文件,添加監控Redis實例信息和故障轉移設置;配置Redis實例配置文件,啟用集群模式並指定集群信息文件路徑;創建nodes.conf文件,包含各Redis實例的信息;啟動集群,執行create命令創建集群並指定副本數量;登錄集群執行CLUSTER INFO命令驗證集群狀態;使

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

如何清空 Redis 數據:使用 FLUSHALL 命令清除所有鍵值。使用 FLUSHDB 命令清除當前選定數據庫的鍵值。使用 SELECT 切換數據庫,再使用 FLUSHDB 清除多個數據庫。使用 DEL 命令刪除特定鍵。使用 redis-cli 工具清空數據。

要從 Redis 讀取隊列,需要獲取隊列名稱、使用 LPOP 命令讀取元素,並處理空隊列。具體步驟如下:獲取隊列名稱:以 "queue:" 前綴命名,如 "queue:my-queue"。使用 LPOP 命令:從隊列頭部彈出元素並返回其值,如 LPOP queue:my-queue。處理空隊列:如果隊列為空,LPOP 返回 nil,可先檢查隊列是否存在再讀取元素。

PHP成為許多網站首選技術棧的原因包括其易用性、強大社區支持和廣泛應用。 1)易於學習和使用,適合初學者。 2)擁有龐大的開發者社區,資源豐富。 3)廣泛應用於WordPress、Drupal等平台。 4)與Web服務器緊密集成,簡化開發部署。
