引入依赖

  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. Linux mount命令

    mount 1.作用 mount命令的作用是加载文件系统,它的用权限是超级用户或/etc/fstab中允许的使用者. 2.格式 mount -a [-fv] [-t vfstype] [-n] [-r ...

  2. unity的三种update

    void FixedUpdate () 固定更新 void Update ()        更新 void LateUpdate()  晚于更新 FixedUpdate () 和 Update () ...

  3. Lecture 5

  4. 牛客训练五:炫酷路途(c++与dp)

    题目链接:传送门 思路:每隔2^i(0<=i<=INF)就有一条路径,所以可以将从头到尾的路线视为一个有向图, 将ai,bi以此输入,然后将路径从小到大排序,不断更新路径. __built ...

  5. vue中的路由嵌套

    1定义组件 const Index = { template:` <div>首页</div> ` } const Order = { template:` <div> ...

  6. BZOJ 1029 [JSOI2007]建筑抢修 (贪心 + 优先队列)

    1029: [JSOI2007]建筑抢修 Time Limit: 4 Sec  Memory Limit: 162 MBSubmit: 5452  Solved: 2422[Submit][Statu ...

  7. VS2013利用ajax访问不了json文件——VS2013配置webconfig识别json文件

    这两天用VS2013开发工具来访问json文件,老是报404文件,我根据网上来设置IIS添加MIME重启IIS和VS2013还是失败,无法访问json文件,但是奇怪的是可以访问txt文件 查询了很多方 ...

  8. 顺序表[A+B->A]

    题目:表A 1  3  5,表B 2 4 6,都呈非递减排序,现将两个表合并成一个表,也呈非递减排序,存放在A中(或者B中),言外之意是不能开辟新表!拿出B中数据,沿着A的后面一直往前比较,如果小于就 ...

  9. 第一章javascript词法结构笔记摘要

    语法介绍 javascript最流行的脚本语言,用于web和HTML,服务器.pc.移动端 轻量级语言,可以插入HTML页面,由浏览器按编写顺序执行 一.字符集 用Unicode字符集编写,是ASCI ...

  10. android 线程中断的处理

    android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4 ...