redis 在spring boot工程中的应用(二)

http://wiselyman.iteye.com/blog/2184884 在spring boot 中加入redis换成的样例

http://www.tuicool.com/articles/qyEvYnR  Spring Boot使用redis做数据缓存
http://www.myexception.cn/other/1938770.html   Spring Boot使用redis作数据缓存

================  以上都是基于注解,不是自定义的,因此不能满足我目前工作的需求

http://www.tuicool.com/articles/BFFB7r   Spring+Jedis+Redis自定义模板实现缓存Object对象 :这个已经提供一种自定义的方法了




接下来介绍一下Redis一种实现方法:
先在application.properties中写入如下配置
spring.redis.database=0
spring.redis.host=172.16.22.21
spring.redis.password= # Login password of the redis server.
spring.redis.pool.max-active=3000
spring.redis.pool.max-idle=1000
spring.redis.pool.max-wait=1500
spring.redis.pool.min-idle=0
spring.redis.port=6379
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0

在configure中写入一下配置信息
import java.lang.reflect.Method;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;



@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
  @Value("${spring.redis.host}")
  private String host;
  @Value("${spring.redis.port}")
  private int port;
  @Value("${spring.redis.timeout}")
  private int timeout;
  
  @Bean
  public KeyGenerator wiselyKeyGenerator(){  
      return new KeyGenerator() {
          @Override  
          public Object generate(Object target, Method method, Object... params) {  
              StringBuilder sb = new StringBuilder();  
              sb.append(target.getClass().getName());  
              sb.append(method.getName());  
              for (Object obj : params) {  
                  sb.append(obj.toString());  
              }  
              return sb.toString();  
          }  
      };  
  }  
  
  @Bean
  public JedisConnectionFactory JedisConnectionFactory() {
      JedisConnectionFactory factory = new JedisConnectionFactory();
      factory.setHostName(host);
      factory.setPort(port);
      factory.setTimeout(timeout); //设置连接超时时间
      return factory;
  }
  //针对特定的类进行序列化缓存,定义对应的bean ============= 对于序列化会存在许多问题,我在第(三)中会慢慢做总结
  @Bean(name="redisTemplateLocationMonitor")
  public RedisTemplate<String, LocationMonitor> redisTemplateLocationMonitor() {
	  RedisTemplate<String, LocationMonitor> redisTemplate = new RedisTemplate<String, LocationMonitor>();
	  redisTemplate.setConnectionFactory(JedisConnectionFactory());
	  Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
	  ObjectMapper om = new ObjectMapper();  
     om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
     om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
     jackson2JsonRedisSerializer.setObjectMapper(om);  
     redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 
     redisTemplate.afterPropertiesSet();  
    
     redisTemplate.setKeySerializer(new StringRedisSerializer());
     redisTemplate.setHashKeySerializer(new GenericToStringSerializer<Object>(Object.class));
     return redisTemplate;
  }
  

//这个函数是通用的,但是如果换成的类有多种,并且在一个service中要调用多种redisTemplate,就要写对应的Bean
  @Bean(name="redisTemplate")
  public RedisTemplate<Object, Object> redisTemplate() {
	  RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
	  redisTemplate.setConnectionFactory(JedisConnectionFactory());
	  Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
	  ObjectMapper om = new ObjectMapper();  
     om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
     om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
     jackson2JsonRedisSerializer.setObjectMapper(om);  
     redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 
     redisTemplate.afterPropertiesSet();  
    
     redisTemplate.setKeySerializer(new StringRedisSerializer());
     redisTemplate.setHashKeySerializer(new GenericToStringSerializer<Object>(Object.class));
     return redisTemplate;
  }
  
  @Bean(name="cacheManager")
  public CacheManager cacheManager() {
	  
	  return new RedisCacheManager(redisTemplate());
  }
  
  
  public void setSerializer(StringRedisTemplate template) {
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      jackson2JsonRedisSerializer.setObjectMapper(om);
      template.setValueSerializer(jackson2JsonRedisSerializer);
  }
  
}

以下是对应的自定义缓存方法:先看接口
public interface LocationMonitorRedis  {
	
	/*
	 * 持久化Redis中缓存的定位信息
	 */
	public void saveToPSQ();
	/*
	 * 向Redis中缓存一条定位信息
	 */
	public void save(LocationMonitor locationMonitor);

	
}

写实现函数
@Service
public class LocationMonitorRedisImpl implements LocationMonitorRedis {

	@Resource
	private RedisTemplate<String, LocationMonitor> redisTemplate;

	private final LocationMonitorRepository locationMonitorRepository;
	
	@Autowired
	public LocationMonitorRedisImpl(LocationMonitorRepository locationMonitorRepository) {
		this.locationMonitorRepository = locationMonitorRepository;
	}
	
	//把数据持久化(可以根据自己情况实现,这里用jpa)
	@Override
	public void saveToPSQ() {
		String pattern = "bak.LocationMonitor.*"; //模式串
		Set<String> keys = redisTemplate.keys(pattern);//找出所有匹配的键
		List<LocationMonitor> lmList = new ArrayList<LocationMonitor>(); 
		Iterator<String> it = keys.iterator();
		while(it.hasNext()){
			String key = it.next();
			LocationMonitor lm = redisTemplate.opsForValue().get(key);//取出所有对应的缓存类的数据
			lmList.add(lm);
		}
		locationMonitorRepository.save(lmList);//持久化
		redisTemplate.delete(keys);//删除键
	}
	@Override
	public void save(LocationMonitor locationMonitor) {
		if(locationMonitor != null){
			Long now = System.currentTimeMillis();  
			String key = "bak.LocationMonitor."+locationMonitor.getId()+"."+now;  //构建键值
			redisTemplate.opsForValue().set(key, locationMonitor);
			key = "LocationMonitor."+locationMonitor.getCorrectionAll().getId();
			redisTemplate.opsForValue().set(key, locationMonitor);   //保存
		} else {
			System.out.println("传来的对象为空!!!");
			return ;
		}
		
	}

}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GDRetop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值