Spring整合Redis缓存实例

一、Redis介绍

什么是Redis?

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

它有什么特点?

(1)Redis数据库完全在内存中,使用磁盘仅用于持久性。
(2)相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。
(3)Redis可以将数据复制到任意数量的从服务器。

Redis 优势?

(1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。
(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。

Redis 缺点?

(1)单线程

(2)耗内存

二、代码实例

引入jar包

配置bean类:RedisConfiguration.java(也可在application-context.xml配置)

package com.kilomob.powernetwork.cache.redis;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis InitConfiguration Bean
 * 
 *   
 * @author fengjk  
 * @date 2017年4月11日
 * @since 1.0
 */
@Configuration
@EnableCaching
public class RedisConfiguration {
	private static final Logger logger = LoggerFactory
			.getLogger(RedisConfiguration.class);

	@Autowired
	private RedisConfig redisConfig;

	@Autowired
	JedisPoolConfig jedisPoolConfig;

	@Bean
	public JedisPoolConfig jedPoolConfig() {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxIdle(redisConfig.maxIdle);
		poolConfig.setMaxWaitMillis(redisConfig.maxWait);
		poolConfig.setMaxTotal(redisConfig.maxTotal);
		return poolConfig;
	}

	@Bean
	public JedisConnectionFactory redisConnectionFactory() {
		JedisConnectionFactory jcf =null;
		if (redisConfig.isSentinel) {
			try {
				ResourcePropertySource propertySource = new ResourcePropertySource("resource", "classpath:application.properties");
				RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(propertySource);
				
				jcf = new JedisConnectionFactory(sentinelConfig, jedisPoolConfig);
				jcf.setTimeout(redisConfig.maxWait);
//				jcf.setPassword(redisConfig.password);
			} catch (IOException e) {
				logger.error("confile not exist or error:",e);
			} 
			
		} else {
			jcf = new JedisConnectionFactory(jedisPoolConfig);
			jcf.setHostName(redisConfig.hostName);
			jcf.setPort(redisConfig.port);
//			jcf.setPassword(redisConfig.password);
			jcf.setTimeout(redisConfig.timeout);
			jcf.setUsePool(true);
		}
		return jcf;
	}


	@SuppressWarnings("rawtypes")
	@Bean
	public RedisTemplate redisTemplate() {
		RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
		redisTemplate.setConnectionFactory(redisConnectionFactory());
//		redisTemplate.setEnableTransactionSupport(true);
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		
		//jdk序列化
		RedisSerializer<Object> redisSerializer = new JdkSerializationRedisSerializer();
		
		redisTemplate.setKeySerializer(stringRedisSerializer);
		redisTemplate.setValueSerializer(redisSerializer);
		
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		redisTemplate.setHashValueSerializer(stringRedisSerializer);
		
		
		redisTemplate.setExposeConnection(true);
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

	@Bean
	public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
		RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
		cacheManager.setDefaultExpiration(60 * 60);
		return cacheManager;
	}
}
配置文件:application.properties
# REDIS (RedisProperties)  
redis.hostname=***.**.***.***
redis.port=6379
redis.password=pw
redis.pool.maxTotal=600
redis.pool.maxIdle=100
redis.pool.maxWait=5000
redis.getConnection.timeout=6000
redis.pool.testOnBorrow=true
redis.is_sentinel=false
redis.maxRedirects=3

spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=***.**.***.***:26379,***.**.***.***:26379
通过注解获取配置文件值
package com.kilomob.powernetwork.cache.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 
 * 
 *   
 * @author fengjk  
 * @date 2017年4月11日
 * @since 1.0
 */
@Component
public class RedisConfig {
	/**
     * redis的地址
     */
	@Value("${redis.hostname}")
	public String hostName;
	/**
     * redis的端口
     */
	@Value("${redis.port}")
	public int port;
	/**
     * redis的密码
     */
	@Value("${redis.password}")
	public String password;
	/**
     * redis连接池
     */
	@Value("${redis.pool.maxTotal}")
	public int maxTotal;
	/**
     * redis连接池
     */
	@Value("${redis.pool.maxIdle}")
	public int maxIdle;
	/**
     * redis连接池
     */
	@Value("${redis.pool.maxWait}") 
	public int maxWait;
	
    /**
     * 是否使用redis集群
     */
    @Value("${redis.is_sentinel}") 
    public boolean isSentinel;
    
    @Value("${redis.maxRedirects}")
    public int maxRedirects;
    
    @Value("${redis.getConnection.timeout}")
	public int timeout;
    
}
使用工具类:
package com.mucfc.msm.common;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * @author fengjk  
 * @date 2017年4月11日
 * @since 1.0
 */
public final class RedisUtil {
	private Logger logger = Logger.getLogger(RedisUtil.class);
	private RedisTemplate<Serializable, Object> redisTemplate;

	/**
	 * 批量删除对应的value
	 * 
	 * @param keys
	 */
	public void remove(final String... keys) {
		for (String key : keys) {
			remove(key);
		}
	}

	/**
	 * 批量删除key
	 * 
	 * @param pattern
	 */
	public void removePattern(final String pattern) {
		Set<Serializable> keys = redisTemplate.keys(pattern);
		if (keys.size() > 0)
			redisTemplate.delete(keys);
	}

	/**
	 * 删除对应的value
	 * 
	 * @param key
	 */
	public void remove(final String key) {
		if (exists(key)) {
			redisTemplate.delete(key);
		}
	}

	/**
	 * 判断缓存中是否有对应的value
	 * 
	 * @param key
	 * @return
	 */
	public boolean exists(final String key) {
		return redisTemplate.hasKey(key);
	}

	/**
	 * 读取缓存
	 * 
	 * @param key
	 * @return
	 */
	public Object get(final String key) {
		Object result = null;
		ValueOperations<Serializable, Object> operations = redisTemplate
				.opsForValue();
		result = operations.get(key);
		return result;
	}

	/**
	 * 写入缓存
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(final String key, Object value) {
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate
					.opsForValue();
			operations.set(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 写入缓存
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(final String key, Object value, Long expireTime) {
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate
					.opsForValue();
			operations.set(key, value);
			redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public void setRedisTemplate(
			RedisTemplate<Serializable, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
}
文章采用写类的方式配置redis,相对比较难理解,读者可以先看下其他方式再回头来巩固一下比较容易吸收。部分摘自其他出处,如有笔误,请及时联系笔者,万分感谢!欢迎加QQ群探讨学习:583138104




  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值