本文共 2525 字,大约阅读时间需要 8 分钟。
Spring-Data-Redis项目(简称SDR)对Redis的Key-Value数据存储操作提供了更高层次的抽象,类似于Spring Framework对JDBC支持一样。关于Spring-Data-Reids的介绍请移步这里(http://docs.spring.io/spring-data/redis/docs/1.4.0.RELEASE/reference/html/ 和这里 http://www.tuicool.com/articles/3aAbMz)。本文只是简单的介绍SpringBoot和SpringDataRedis的集成。
@Bean private JedisConnectionFactory getJedisConnectionFactory(){ String[] strServer = redisArguments.getServerName().split(":"); JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(strServer[0]); jedisConnectionFactory.setPort(Integer.parseInt(strServer[1])); jedisConnectionFactory.setTimeout(redisArguments.getTimeout()); return jedisConnectionFactory; }这里可以配置需要的配置:如JedisPoolConfig、JedisCluster、JedisShardInfo。
package com.zkn.learnspringboot.redis;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Component;/** * Created by zkn on 2016/8/21. */@Componentpublic class RedisTemplementFactory { @Autowired private JedisConnectionFactory jedisConnectionFactory; @Bean private StringRedisTemplate getStringRedisTemplate(){ return new StringRedisTemplate(jedisConnectionFactory); }}这里我用了StringRedisTemplate来对字符串进行操作。
@Autowired private StringRedisTemplate stringRedisTemplate; @RequestMapping("putSpringRedisTemplemetSave.do") public String putSpringRedisTemplemet(){ ValueOperations valueOperations = stringRedisTemplate.opsForValue(); StringRedisSerializer serializer = new StringRedisSerializer(); stringRedisTemplate.setKeySerializer(serializer); stringRedisTemplate.setValueSerializer(serializer); PersonDomain personDomain = new PersonDomain(); personDomain.setId(1); personDomain.setPassWord("zhangsanlisia"); personDomain.setUserName("张三娜丽丝"); valueOperations.set("1",personDomain.getUserName()); return "保存成功了!!!!"; }取出刚才保存的字符串
@RequestMapping("getSpringRedisTemplemetSave.do") public String getSpringRedisTemplemet(HttpServletRequest request){ String str = request.getParameter("key"); ValueOperations valueOperations = stringRedisTemplate.opsForValue(); return (String) valueOperations.get(str); }