引入依赖

  Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通过引入spring-boot-starter-redis来配置依赖关系。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

参数配置

  在application.properties中加入Redis服务端的相关配置,具体说明如下:

# Redis数据库索引(默认为0)
spring.redis.database=
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=
# 连接超时时间(毫秒)
spring.redis.timeout=

  其中spring.redis.database的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16,可以理解为数据库的schema

测试访问

  通过编写测试用例,举例说明如何访问Redis。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests { @Autowired
private StringRedisTemplate stringRedisTemplate; @Test
public void test() throws Exception { // 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "");
Assert.assertEquals("", stringRedisTemplate.opsForValue().get("aaa")); } }

  上面的例子中,我们使用StringRedisTemplate对象进行Redis的读写操作,该对象从命名中就可注意到支持的是String类型。如果有使用过spring-data-redis的开发者一定熟悉RedisTemplate<K, V>接口,StringRedisTemplate就相当于RedisTemplate<String, String>的实现。

  除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplate<String, User>来初始化并进行操作。但是Spring Boot并不支持直接使用,需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化,下面我们通过一个实例来完成对象的读写操作。

  创建要存储的对象:User

public class User implements Serializable {

    private static final long serialVersionUID = -1L;

    private String username;
private Integer age; public User(String username, Integer age) {
this.username = username;
this.age = age;
} // 省略getter和setter }

  实现对象的序列化接口

public class RedisObjectSerializer implements RedisSerializer<Object> {

  private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter(); static final byte[] EMPTY_ARRAY = new byte[]; public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
} try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
} public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
} try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
} private boolean isEmpty(byte[] data) {
return (data == null || data.length == );
}
}

  配置针对User的RedisTemplate实例

@Configuration
public class RedisConfig { @Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
} @Bean
public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, User> template = new RedisTemplate<String, User>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
} }

测试案例:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests { @Autowired
private RedisTemplate<String, User> redisTemplate; @Test
public void test() throws Exception { // 保存对象
User user = new User("u1", );
redisTemplate.opsForValue().set(user.getUsername(), user); Assert.assertEquals(, redisTemplate.opsForValue().get("u1").getAge().longValue()); } }

更加详细的spring data redis操作,请参考:https://docs.spring.io/spring-data/redis/docs/1.6.2.RELEASE/reference/html/

 

Spring Boot中使用Redis数据库的更多相关文章

  1. Spring Boot中使用MongoDB数据库

    前段时间分享了关于Spring Boot中使用Redis的文章,除了Redis之后,我们在互联网产品中还经常会用到另外一款著名的NoSQL数据库MongoDB. 下面就来简单介绍一下MongoDB,并 ...

  2. spring boot 中使用redis session

    spring boot 默认的httpsession是存在内存中.这种默认方式有几个缺点:1.当分布式部署时,存在session不一致的问题:2.当服务重启时session就会丢失,这时候用户就需要重 ...

  3. Spring Boot中使用PostgreSQL数据库

    在如今的关系型数据库中,有两个开源产品是你必须知道的.其中一个是MySQL,相信关注我的小伙伴们一定都不陌生,因为之前的Spring Boot关于关系型数据库的所有例子都是对MySQL来介绍的.而今天 ...

  4. 【Spring Boot&&Spring Cloud系列】Spring Boot中使用NoSql数据库Redis

    github地址:https://github.com/AndyFlower/Spring-Boot-Learn/tree/master/spring-boot-nosql-redis 一.加入依赖到 ...

  5. Spring Boot中使用Redis小结

    Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, 等. Redis简单介绍 Redi ...

  6. Spring Boot中使用redis的发布/订阅模式

    原文:https://www.cnblogs.com/meetzy/p/7986956.html redis不仅是一个非常强大的非关系型数据库,它同时还拥有消息中间件的pub/sub功能,在sprin ...

  7. Spring Boot 中集成 Redis 作为数据缓存

    只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...

  8. Spring Boot中使用时序数据库InfluxDB

    除了最常用的关系数据库和缓存之外,之前我们已经介绍了在Spring Boot中如何配置和使用MongoDB.LDAP这些存储的案例.接下来,我们继续介绍另一种特殊的数据库:时序数据库InfluxDB在 ...

  9. spring boot 中使用 Redis 与 Log

    spring boot + mybatis + redis 配置 1.application.yml #配置访问的URLserver: servlet-path: /web port: spring: ...

随机推荐

  1. MathExam

    MathExam 一.预估与实际 PSP2.1 Personal Software Process Stages 预估耗时(分钟) 实际耗时(分钟) Planning 计划 575 605 • Est ...

  2. 1.The Necessity of a Broad Education 全面教育的必要性

    1.The Necessity of a Broad Education 全面教育的必要性 (1) According to a survey,which was based on the respo ...

  3. 常用.bat

    休眠.bat rundll32 powrprof.dll,SetSuspendState 常用.bat start /d  "d:\Program Files (x86)\Tencent\T ...

  4. CodeForces 916B Jamie and Binary Sequence (changed after round) (贪心)

    题意:给定两个数字n,m,让你把数字 n 拆成一个长度为 m 的序列a1,a2,a3...am,并且∑2^ai = n,如果有多组,要求序列中最大的数最小,然后再相同就要求除了最大数字典序最大. 析: ...

  5. Java四种排序:冒泡,选择,插入,二分(折半插入)

    四种排序:冒泡,选择,插入,二分(折半插入) public class Test{ // public static void main(String[] args) { // Test t=new ...

  6. python-Django-01基础配置

    参考资料地址 http://www.ziqiangxuetang.com/django/django-install.html 官方文档 一: 1先下载Django源码包,下载地址https://ww ...

  7. poj2774 sa模版

    学习地址:http://blog.csdn.net/yxuanwkeith/article/details/50636898 #include<iostream> #include< ...

  8. 关于Linux学习中的问题和体会

    本科期间未开展过与之相关的课程,所以初次接触Linux难免有些问题!参照老师给的学习资料中内容,逐步解决了一些问题,但还有一些问题没解决,下面列举出自己遇到的一些问题. 1.在环境变量与文件查找专题中 ...

  9. sublime text配置node.js调试

    1. 首先到 nodejs.org 下载 Node.js 安装包并安装.2. 打开 Sublime Text 2 编辑器.选择菜单 Tools --> Build System --> n ...

  10. C#期末大作业 消消乐 2017-06-01 18:11 275人阅读 评论(0) 收藏

    邻近期末,忙于刷题之余意识到期末大作业来不及了,匆匆赶下了作业,虽说做的很是粗糙,但完全原创的 下载链接 https://pan.baidu.com/s/1cCNLr4 大体的做大约3天完成了: 第一 ...