引入依赖

  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. Mac下Maven安装与配置

    Mac下Maven安装与配置 下载maven http://maven.apache.org/download.cgi main->download菜单下的Files 下载后解压在Documen ...

  2. 使用小技巧加快IDEA的开发速度

    一.live template的使用. 1.live template(自定义模板的载入)打开: Ctrl+shift+A 再在命令行中间输入live  template弹出用户自定义的界面.需要自行 ...

  3. Hadoop3集群搭建之——hive添加自定义函数UDF

    上篇: Hadoop3集群搭建之——虚拟机安装 Hadoop3集群搭建之——安装hadoop,配置环境 Hadoop3集群搭建之——配置ntp服务 Hadoop3集群搭建之——hive安装 Hadoo ...

  4. 2018.11.24 poj3415Common Substrings(后缀数组+单调栈)

    传送门 常数实在压不下来(蒟蒻开O(3)都过不了). 但有正确性233. 首先肯定得把两个字符串接在一起. 相当于heightheightheight数组被height<kheight<k ...

  5. Java基础-时间类

    关于java中六个时间类的使用和区别 java.util.Date java.sql.Date ,java.sql.Time , java.sql.Timestamp java.text.Simple ...

  6. IDEA有用插件总结

    IDEA要查看哪些插件起效了可以通过.IntellijIdeaXxx/config/plugins/availables.xml里查看: 一:Lombok插件,里面很多注解都可以省略许多冗余的代码: ...

  7. Nodejs 传图片的两种方式

    node上传图片第一种方式 1,首先引入模块 "connect-multiparty": "~1.2.5", 在package.json中添加 "co ...

  8. 1、JavaScript 基础一 (从零学习JavaScript)

    1:定义:javascript是一种弱类型.动态类型.解释型的脚本语言. 弱类型:类型检查不严格,偏向于容忍隐式类型转换. 强类型:类型检查严格,偏向于不容忍隐式类型转换. 动态类型:运行的时候执行类 ...

  9. 20155205 2016-2017-2 《Java程序设计》第6周学习总结

    20155205 2016-2017-2 <Java程序设计>第6周学习总结 教材学习内容总结 第十章 在Java中,输入串流代表对象为Java.io.InputStream实例,输出串流 ...

  10. Kafka C++客户端库librdkafka笔记

    目录 目录 1 1. 前言 2 2. 缩略语 2 3. 配置和主题 3 3.1. 配置和主题结构 3 3.1.1. Conf 3 3.1.2. ConfImpl 3 3.1.3. Topic 3 3. ...