Spring Boot中使用Redis数据库
引入依赖
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数据库的更多相关文章
- Spring Boot中使用MongoDB数据库
前段时间分享了关于Spring Boot中使用Redis的文章,除了Redis之后,我们在互联网产品中还经常会用到另外一款著名的NoSQL数据库MongoDB. 下面就来简单介绍一下MongoDB,并 ...
- spring boot 中使用redis session
spring boot 默认的httpsession是存在内存中.这种默认方式有几个缺点:1.当分布式部署时,存在session不一致的问题:2.当服务重启时session就会丢失,这时候用户就需要重 ...
- Spring Boot中使用PostgreSQL数据库
在如今的关系型数据库中,有两个开源产品是你必须知道的.其中一个是MySQL,相信关注我的小伙伴们一定都不陌生,因为之前的Spring Boot关于关系型数据库的所有例子都是对MySQL来介绍的.而今天 ...
- 【Spring Boot&&Spring Cloud系列】Spring Boot中使用NoSql数据库Redis
github地址:https://github.com/AndyFlower/Spring-Boot-Learn/tree/master/spring-boot-nosql-redis 一.加入依赖到 ...
- Spring Boot中使用Redis小结
Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, 等. Redis简单介绍 Redi ...
- Spring Boot中使用redis的发布/订阅模式
原文:https://www.cnblogs.com/meetzy/p/7986956.html redis不仅是一个非常强大的非关系型数据库,它同时还拥有消息中间件的pub/sub功能,在sprin ...
- Spring Boot 中集成 Redis 作为数据缓存
只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...
- Spring Boot中使用时序数据库InfluxDB
除了最常用的关系数据库和缓存之外,之前我们已经介绍了在Spring Boot中如何配置和使用MongoDB.LDAP这些存储的案例.接下来,我们继续介绍另一种特殊的数据库:时序数据库InfluxDB在 ...
- spring boot 中使用 Redis 与 Log
spring boot + mybatis + redis 配置 1.application.yml #配置访问的URLserver: servlet-path: /web port: spring: ...
随机推荐
- kbmmw 的HTTPSmartService中的跨域访问
有同学在使用kbmmw 与extjs 结合的时候,涉及到了跨域访问,这个在 kbmmw 里面已经完全解决. extjs 在访问跨域的时候,首先会使用OPIONS 调用,服务端要根据浏览器请求的 he ...
- ubuntu安装rubyOnRails
https://gorails.com/setup/ubuntu/16.04#ruby-rbenv 文章很详细
- 23.Xcode中常用的快捷键操作
1.工程导航器:command+1 浏览文件夹,控制器,图片等 2.显示/隐藏导航器面板:Command+0 隐藏左边工具栏 3.显示/隐藏实用工具面板:Command+Option+0 使用工具面板 ...
- 第04章:MongoDB基本概念
① 数据库 MongoDB的一个实例可以拥有一个或多个相互独立的数据库,每个数据库都有自己的集合 集合 集合可以看作是拥有动态模式的表 文档 文档是MongoDB中基本的数据单元,类似于RDB ...
- UVaLive 3641 Leonardo's Notebook (置换)
题意:给定一个置换 B 问是否则存在一个置换 A ,使用 A^2 = B. 析:可以自己画一画,假设 A = (a1, a2, a3)(b1, b2, b3, b4),那么 A^2 = (a1, a2 ...
- react优化--pureComponent
shouldComponentUpdate的默认渲染 在React Component的生命周期中,shouldComponentUpdate方法,默认返回true,也就意味着就算没有改变props或 ...
- 一些js在线引用文档
1.jquery在线引用: <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script& ...
- C和C++中的volatile、内存屏障和CPU缓存一致性协议MESI
目录 1. 前言2 2. 结论2 3. volatile应用场景3 4. 内存屏障(Memory Barrier)4 5. setjmp和longjmp4 1) 结果1(非优化编译:g++ -g -o ...
- 【2】C#读取文本文件
一.读取
- MFC源码实现文件对照表
CDocManager类[实现文件] /SRC/DOCTEMPL.CPP CSingleDocTemplate类[实现文件] /SRC/DOCSINGL.CPP CWinApp::OnFileOpen ...