Redis是key-value存储的非关系型数据库。Spring Data Redis包含了多个模板实现,用来完成Redis数据库的数据存取功能

1、如何连接Redis?

Spring Data Redis提供了JedisConnectFactory连接工厂(不止这一个)

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.1.106"></property>
</bean>

2、使用模板

  Spring Data Redis提供了RedisTemplate 和 StringRedisTemplate模板。模板封装了对redis操作,提供了较高级的数据访问方案。从名字可以看出后者只关注字符串类型,当redis的key和value都是字符串时候建议使用StringRedisTemplate

RedisTemplate的很多功能以子API的形式提供,他们区分了单个值和集合值得场景。

package com.cn.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import java.util.List;
import java.util.Set; @Component
public class JedisUtil { @Autowired
private RedisTemplate<String, Object> redisTemplate; //字符串
public void setStr(String key, Object value){
redisTemplate.opsForValue().set(key, value);
}
public Object getStr(String key){
return redisTemplate.opsForValue().get(key);
}
//list集合
public void lpush(String key, Object value){
redisTemplate.opsForList().leftPush(key, value);
}
public Object lpop(String key){
return redisTemplate.opsForList().leftPop(key);
}
public List<Object> lrange(String key, long start , long end){
return redisTemplate.opsForList().range(key, start, end);
}
//set集合
public void addSet(String key, String value){
redisTemplate.opsForSet().add(key, value);
}
public Set<Object> getSet(String key){
return redisTemplate.opsForSet().members(key);
}
//hash集合
public void hset(String key, String key1, String value){
redisTemplate.opsForHash().put(key, key1, value);
}
public Object hget(String key, String key1){
return redisTemplate.opsForHash().get(key, key1);
}
public Set<Object> getKeys(String key){
return redisTemplate.opsForHash().keys(key);
} }

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:springMvc.xml", "classpath:spring-source.xml"})
public class JedisUtilTest { @Autowired
private JedisUtil jedisUtil; @Test
public void setStr() throws Exception {
jedisUtil.setStr("shoudu","beijing");
} @Test
public void getStr() throws Exception {
Object obj=jedisUtil.getStr("shoudu");
System.out.println(obj);
} @Test
public void lpush() throws Exception {
jedisUtil.lpush("testlist",new User("ii","ll")); } @Test
public void lpop() throws Exception {
Object obj= jedisUtil.lpop("testlist");
System.out.println(obj);
} @Test
public void lrange() throws Exception {
List<Object> list=jedisUtil.lrange("testlist", 0 , -1);
System.out.println(list);
} @Test
public void addSet() throws Exception {
jedisUtil.addSet("testset", "jj2");
} @Test
public void getSet() throws Exception {
Object obj = jedisUtil.getSet("testset");
System.out.println(obj);
} @Test
public void hset() throws Exception {
jedisUtil.hset("testhash", "name", "liming");
} @Test
public void hget() throws Exception {
Object obj=jedisUtil.hget("testhash","name");
System.out.println(obj);
} @Test
public void getKeys() throws Exception {
Set<Object> keys=jedisUtil.getKeys("testhash");
System.out.println(keys);
} @Test
public void muchOps() throws Exception{
BoundHashOperations<String, String, Object> boundHashOperations=
jedisUtil.redisTemplate.boundHashOps("testhash");
String str=boundHashOperations.getKey();
System.out.println(str);
Object obj=boundHashOperations.get("name");
System.out.println(obj);
boundValueOperations.put("age",123);
boundValueOperations.put("school","beida");
Set<String> keys=boundHashOperations.keys();
System.out.println(keys);
}
}

  以上测试方法,仅仅测试了每种redis数据类型的部分方法。注意,最后muchOps()测试方法,redisTemplate提供绑定key(此处为hash类型的key,其它类型类似)的方式执行操作,整个方法中仅仅一个地方使用了key,即jedisUtil.redisTemplate.boundHashOps("testhash"),对返回的boundValueOperations执行的所有操作都会应用到这个key上。

3、使用key和value的序列化器

  当某个key-value条目保存到Redis存储时候,key和value都会使用Redis序列化器进行序列化。Spring Date Redis 提供了多个序列化器:

1)JdkSerializationRedisSerializer:POJO对象的存取场景,使用JDK本身序列化机制,将pojo类通过ObjectInputStream/ObjectOutputStream进行序列化操作,最终redis-server中将存储字节序列。是目前最常用的序列化策略。
2)StringRedisSerializer:Key或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封装。是最轻量级和高效的策略。
3)JacksonJsonRedisSerializer:jackson-json工具提供了javabean与json之间的转换能力,可以将pojo实例序列化成json格式存储在redis中,也可以将json格式的数据转换成pojo实例。因为jackson工具在序列化和反序列化时,需要明确指定Class类型,因此此策略封装起来稍微复杂。【需要jackson-mapper-asl工具支持】
4)OxmSerializer:提供了将javabean与xml之间的转换能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存储的数据将是xml工具。不过使用此策略,编程将会有些难度,而且效率最低;不建议使用。【需要spring-oxm模块的支持

  • RedisTemplate中需要声明4种serializer,默认为“JdkSerializationRedisSerializer”:

a) keySerializer :对于普通K-V操作时,key采取的序列化策略
    b) valueSerializer:value采取的序列化策略
    c) hashKeySerializer: 在hash数据结构中,hash-key的序列化策略
    d) hashValueSerializer:hash-value的序列化策略

  • StringRedisTemplate也需要申明4中serializer,但是默认为“StringRedisSerializer”,可以看StringRedisTemplate类的源码:
package org.springframework.data.redis.core;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; public class StringRedisTemplate extends RedisTemplate<String, String> {
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer(); //StringRedisSerializer序列器
this.setKeySerializer(stringSerializer);
this.setValueSerializer(stringSerializer);
this.setHashKeySerializer(stringSerializer);
this.setHashValueSerializer(stringSerializer);
} public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
this.setConnectionFactory(connectionFactory);
this.afterPropertiesSet();
} protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}

spring-集成redis的更多相关文章

  1. Spring集成Redis集群(含spring集成redis代码)

    代码地址如下:http://www.demodashi.com/demo/11458.html 一.准备工作 安装 Redis 集群 安装参考: http://blog.csdn.net/zk6738 ...

  2. spring 集成 redis -- pub/sub

    redis除了常用的当做缓存外,还可以当做简单的消息中间件,实现消息发布订阅 spring集成redis,可以使用spring-data-redis 首先引入相关maven依赖(此处我spring相关 ...

  3. spring集成redis

    redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快.常用作缓存和发布-订阅式的消息队列.redis官方没有提供windows版本的软件.windows版本 ...

  4. spring 集成redis客户端jedis(java)

    spring集成jedis简单实例   jedis是redis的java客户端,spring将redis连接池作为一个bean配置. “redis.clients.jedis.JedisPool”,这 ...

  5. spring集成redis,集成redis集群

    原文:http://chentian114.iteye.com/blog/2292323 1.通过spring-data-redis集成redis pom.xml依赖包 <project xml ...

  6. Spring集成Redis方案(spring-data-redis)(基于Jedis的单机模式)(待实践)

    说明:请注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已经去除Jedis的依赖包,需要自行引入,这个是个坑点.并且会与一些低版本的Sp ...

  7. spring集成redis——主从配置以及哨兵监控

    Redis主从模式配置: Redis的主从模式配置是非常简单的,首先我们需要有2个可运行的redis环境: master node : 192.168.56.101 8887 slave node: ...

  8. Spring集成Redis缓存

    作者:13 GItHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. 整合Redis 本来以为类似的Redis教程和整合代码应该会很多,因 ...

  9. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十二)Spring集成Redis缓存

    作者:13 GitHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. 整合Redis 本来以为类似的Redis教程和整合代码应该会很多,因 ...

  10. Spring集成Redis使用注解

    转载:http://blog.csdn.net/u013725455/article/details/52129283 使用Maven项目,添加jar文件依赖: <project xmlns=& ...

随机推荐

  1. Linux文件系统的实现 ZZ

    作者:Vamei 出处:http://www.cnblogs.com/vamei Linux文件管理从用户的层面介绍了Linux管理文件的方式.Linux有一个树状结构来组织文件.树的顶端为根目录(/ ...

  2. 【NLP_Stanford课堂】文本分类2

    一.实验评估参数 实验数据本身可以分为是否属于某一个类(即correct和not correct),表示本身是否属于某一类别上,这是客观事实:又可以按照我们系统的输出是否属于某一个类(即selecte ...

  3. 【转】修复关于apache-xampp的问题:Port 443 in use by “vmware-hostd.exe”!

    在电脑里装了VMware后,再要装xampp,十有八九就会出现这个问题: 11:23:37  [Apache]     Problem detected! 11:23:37  [Apache]    ...

  4. 【Leetcode】【Medium】Search for a Range

    Given a sorted array of integers, find the starting and ending position of a given target value. You ...

  5. 二阶SQL注入理解与体会

    一:SQL注入分类 SQL注入一般分为两类:一阶SQL注入(普通SQL注入),二阶SQL注入 二:二者进行比较 0x01:一阶SQL注入: 1:一阶SQL注入发生在一个HTTP请求和响应中,对系统的攻 ...

  6. css3 box-shadow属性 鼠标移动添加阴影效果

    text-shadow是给文本添加阴影效果,box-shadow是给元素块添加周边阴影效果. 基本语法:{box-shadow:[inset] x-offset  y-offset  blur-rad ...

  7. June 25th 2017 Week 26th Sunday

    There is always that one song that brings back old memories. 总有那么一首歌,让你想起那些旧的回忆. There are seveal so ...

  8. redis持久化那些事(kēng)儿

    这是一篇包含了介绍性质和吐槽性质的日志.主要介绍一下我学习redis持久化时候被坑的经历.redis的使用介绍现在没有打算写,因为比较多,以我如此懒的性格...好吧,还是有点这方面想法的,不过一篇博客 ...

  9. UVa 1608 - Non-boring sequences

    链接: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  10. PHP------面向对象的特性

    面向对象的特性 一.面向对象有三大特性: 封装.继承.多态.(非常重要,第一要记住!!!!!!!!!!) 二.封装 封装就是用来做类的,把一个类封装起来.做类不能随便的做.我们做类不能随便去写一个类, ...