基於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)

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...

Redis在數據存儲和管理中扮演著關鍵角色,通過其多種數據結構和持久化機製成為現代應用的核心。 1)Redis支持字符串、列表、集合、有序集合和哈希表等數據結構,適用於緩存和復雜業務邏輯。 2)通過RDB和AOF兩種持久化方式,Redis確保數據的可靠存儲和快速恢復。

SpringBoot中使用Redis緩存OAuth2Authorization對像在SpringBoot應用中,使用SpringSecurityOAuth2AuthorizationServer...

使用RedisTemplate進行批量查詢時為何返回值為空?在使用RedisTemplate進行批量查詢操作時,可能會遇到返回的結果�...

Redis是一种内存数据结构存储系统,主要用作数据库、缓存和消息代理。它的核心特点包括单线程模型、I/O多路复用、持久化机制、复制与集群功能。Redis在实际应用中常用于缓存、会话存储和消息队列,通过选择合适的数据结构、使用管道和事务、以及进行监控和调优,可以显著提升其性能。

關於RedisTemplate.opsForList().leftPop()不支持傳個數的原因在使用Redis時,很多開發者會遇到一個問題:為什麼redisTempl...

SpringBoot定時任務在多節點環境下的優化方案在開發Spring...

AI可以幫助優化Composer的使用,具體方法包括:1.依賴管理優化:AI分析依賴關係,建議最佳版本組合,減少衝突。 2.自動化代碼生成:AI生成符合最佳實踐的composer.json文件。 3.代碼質量提升:AI檢測潛在問題,提供優化建議,提高代碼質量。這些方法通過機器學習和自然語言處理技術實現,幫助開發者提高效率和代碼質量。
