spring中redis怎么用

spring中redis怎么用

springredis怎么用?

在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> redisTemplate(RedisConnectionFactory cf) { RedisTemplate<string> redisTemplate = new RedisTemplate<string>(); redisTemplate.setConnectionFactory(cf); return redisTemplate; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManger = new RedisCacheManager(redisTemplate); cacheManger.setDefaultExpiration(5); //cache过期时间 return cacheManger; } }</string></string></string>

注意:

设置 Cache 过期时间要合适,太长就长期有效,太短你看不到测试结果。建议 5-20秒。

最后直接在需要添加缓存的方法上使用注解就可实现缓存:

spring中redis怎么用

更多Redis相关知识,请访问Redis使用教程栏目!

以上就是spring中

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享