spring中redis怎麼用?
在Spring中使用Redis
Java中操作Redis使用的是Jedis,首先在pom.xml中加入相關依賴:
<!-- redis cache related.....start --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency> <!-- redis cache related.....end -->
然後實作設定類別:
package com.ehelp.util; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Bean public JedisConnectionFactory redisConnectionactory() { JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); redisConnectionFactory.setHostName("localhost"); redisConnectionFactory.setPort(6379); return redisConnectionFactory; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(cf); return redisTemplate; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManger = new RedisCacheManager(redisTemplate); cacheManger.setDefaultExpiration(5); //cache过期时间 return cacheManger; } }
注意:
設定Cache 過期時間要合適,太長就長期有效,太短你看不到測試結果。建議 5-20秒。
最後直接在需要加入快取的方法上使用註解就可實現快取:
#更多Redis相關知識,請造訪Redis使用教程專欄!
以上是spring中redis怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!