spring中redis的使用方法-创新互联
这篇文章将为大家详细讲解有关spring中redis的使用方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

spring中redis怎么用?
在Spring中使用Redis
Java中操作Redis使用的是Jedis,首先在pom.xml中加入相关依赖:
org.springframework.data spring-data-redis 1.6.0.RELEASE redis.clients jedis 2.7.3 org.apache.commons commons-pool2 2.4.2
然后实现配置类:
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 redisTemplate(RedisConnectionFactory cf) {
RedisTemplate redisTemplate = new RedisTemplate();
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秒。
最后直接在需要添加缓存的方法上使用注解就可实现缓存:

关于spring中redis的使用方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
网站名称:spring中redis的使用方法-创新互联
当前网址:http://www.jxjierui.cn/article/dsjpjg.html


咨询
建站咨询
