当前位置: 首页 > 新闻动态 > 技术教程

spring中redis怎么用

作者:藏色散人 浏览: 发布日期:2019-06-26
[导读]:在Spring中使用Redis:Java中操作Redis使用的是Jedis,首先在pom.xml中加入相关依赖;然后实现配置类;最后直接在需要添加缓存的方法上使用注解就可实现缓存。

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秒。

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

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

免责声明:转载请注明出处:http://sczxchw.cn/news/541352.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!