最近项目中用到Redis,上网查了很多示例,发现或多或少都有问题。踩过很多坑,终于在Spring Boot中成功实现了Redis存储。记录如下,方便别人,也方便自己。

Redis(REmote DIctionary Server) 是一个由Salvatore Sanfilippo写的key-value存储系统。Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

Redis安装

至于在服务器上如何搭建Redis存储系统,本文就不在赘述,网上相关教程很多,请自行Google。如果要实现Redis可远程连接,需要注意一下几点:

  1. 配置文件redis.conf设置Redis可远程访问
  2. 设置登录密码
  3. 设置Redis可在后台运行
  4. 开启防火墙端口,Redis默认端口为6379
  5. 建议设置为开机自启动

Spring Boot中Redis应用

1. 引入依赖

pom.xml文件中依赖如下

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

2. 配置文件

可以利用配置文件进行设置,也可以直接通过注释配置。配置文件application.yml如下:

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

3. 定义RedisTemplate

package com.ygingko.utest.config;

import com.ygingko.utest.config.redis.RedisObjectSerializer;
import com.ygingko.utest.entity.dto.UserDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig; @Configuration
@PropertySource("classpath:application.yml")
public class RedisConfig { @Value("${spring.redis.host}")
private String host; @Value("${spring.redis.port}")
private int port; @Value("${spring.redis.password}")
private String password; @Value("${spring.redis.database}")
private int database; @Value("${spring.redis.timeout}")
private int timeout; @Value("${spring.redis.pool.max-active}")
private int maxActive; @Value("${spring.redis.pool.max-idle}")
private int maxIdle; @Value("${spring.redis.pool.min-idle}")
private int minIdle; @Value("${spring.redis.pool.max-wait}")
private long maxWait; @Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setDatabase(database);
factory.setTimeout(timeout); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(maxActive);
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMinIdle(minIdle);
jedisPoolConfig.setMaxWaitMillis(maxWait); factory.setPoolConfig(jedisPoolConfig); return factory;
} @Bean
public RedisTemplate<String, UserDTO> redisTemplate() {
RedisTemplate<String, UserDTO> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}

4. 实现RedisSerializer接口

package com.ygingko.utest.config.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException; public class RedisObjectSerializer implements RedisSerializer { private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter(); private static final byte[] EMPTY_ARRAY = new byte[0]; @Override
public byte[] serialize(Object o) throws SerializationException {
if (o == null) {
return EMPTY_ARRAY;
} try {
return serializer.convert(o);
} catch (Exception e) {
return EMPTY_ARRAY;
}
} @Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (isEmpty(bytes)) {
return null;
} try {
return deserializer.convert(bytes);
} catch (Exception e) {
throw new SerializationException("Cannot deserialize ", e);
}
} private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}

5. 存数对象

存储对象必须实现Serializable接口,有固定的serialVersionUID。如下:

package com.ygingko.utest.entity.dto;

import com.alibaba.fastjson.JSON;

import java.io.Serializable;

public class UserDTO implements Serializable {
private static final long serialVersionUID = 4044555734385804034L; private Integer uid;
private String name;
private String password;
private Integer level; public Integer getUid() {
return uid;
} public void setUid(Integer uid) {
this.uid = uid;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public Integer getLevel() {
return level;
} public void setLevel(Integer level) {
this.level = level;
} @Override
public String toString() {
return JSON.toJSONString(this);
}
}

6. 应用示例

package com.ygingko.utest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import redis.clients.jedis.Jedis; import java.util.ArrayList;
import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class UtestApplicationTests { @Autowired
private RedisTemplate<String, UserDTO> redisTemplate; @Test
public void testRedis() throws Exception {
UserDTO userBean = new UserDTO();
userBean.setUid(1001);
userBean.setName("huang");
userBean.setLevel(1);
redisTemplate.opsForValue().set("token", userBean);
System.out.println(redisTemplate.opsForValue().get("token"));
} @Test
public void contextLoads() { Jedis jedis = new Jedis("192.168.1.197", 6379);
System.out.println("****************" + jedis.ping());
}
}

redis在spring-boot中的应用的更多相关文章

  1. 【redis】spring boot中 使用redis hash 操作 --- 之 使用redis实现库存的并发有序操作

    示例: @Autowired StringRedisTemplate redisTemplate; @Override public void dealRedis(Dealer dealer) { d ...

  2. spring boot(三):Spring Boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  3. springboot(三):Spring boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  4. Spring Boot:Spring Boot 中 Redis 的使用

    Redis 介绍 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更丰富的数据结构,例如 hashes, lists, sets 等,同时支持数据持久化.除此 ...

  5. (转)Spring Boot(三):Spring Boot 中 Redis 的使用

    http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html Spring Boot 对常用的数据库支持外,对 Nosql ...

  6. Spring boot(三)在Spring boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

  7. Spring Boot(三):Spring Boot 中 Redis 的使用

    Spring Boot 对常用的数据库支持外,对 Nosql 数据库也进行了封装自动化. Redis 介绍 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更 ...

  8. SpringBoot(三) :Spring boot 中 Redis 的使用

    前言: 这一篇讲的是Spring Boot中Redis的运用,之前没有在项目中用过Redis,所以没有太大的感觉,以后可能需要回头再来仔细看看. 原文出处: 纯洁的微笑 SpringBoot对常用的数 ...

  9. Spring Boot 中 Redis 的使用

    Spring Boot 对常用的数据库支持外,对 Nosql 数据库也进行了封装自动化,如Redis.MongoDB等,本文主要介绍Redis的使用. Redis 介绍 Redis 是目前业界使用最广 ...

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

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

随机推荐

  1. win10 uwp 改变鼠标

    经常在应用需要修改光标,显示点击.显示输入,但是有些元素不是系统的,那么如何设置鼠标? 本文主要:UWP 设置光标,UWP 移动鼠标 设置光标 需要写一点代码来让程序比较容易看到,什么光标对于什么. ...

  2. 备忘:有MTU值设置不当导致的部分网站无法访问问题

    如题,有时候突然weibo.com,webQQ等网站网络连接超时,怎么找也没得原因,今天管理电信的光猫,发现设置的MTU的1400,突然想起之前电脑和路由器上设置的MTU是1500,感觉可能是这个问题 ...

  3. 启动tomcat爆错 the JRE could not be found

    启动报错,如下图: 之前更改了了一个较低的jdk的版本看了看一个项目的代码,不知所云,然后再改回来, 混乱之中只要启动Tomcat就出现这种错误,还是无法找到JRE,最后如此解决: 在Windows- ...

  4. Linux系统挂载操作mount详解

    在Linux系统中,文件系统不挂载是无法使用的.挂载,即是让文件系统在操作系统中可用.在Linux中使用mount命令来挂载文件系统,有永久性挂载和临时性挂载两种挂载方式. 1. 永久性挂载: 修改配 ...

  5. MySql数据库的基本原理及指令

    1.什么是数据库 数据库就是存储数据的仓库,其本质是一个文件系统,数据按照特定的格式将数据存储起来,用户可以通过SQL对数据库中的数据进行增加,修改,删除及查询操作. 2.简介 MySQL是一个开放源 ...

  6. Appium python自动化测试系列之页面滑动原理讲解(十)

    10.1.1 页面滑动原理分析 在页面滑动查找章节我们就讲了滑动的知识点,只是不知道大家是否有认真练习以及去理解,如果你认真练习.理解了那么我相信这一章节的东西不用看也能够完成,下面我们还是简单分析一 ...

  7. 通过 ODBC 访问数据库获取数据集

    Step1:(window 中完成): 控制面板/管理工具/ODBC 数据源/用户 Step2:(window 中完成): 添加/SQL Server Step3:(window 中完成): 自己定义 ...

  8. Circle

    Circle   Memory Limit: 32768KB   64bit IO Format: %lld & %llu Status Description Your task is so ...

  9. IdentityServer4实现Token认证登录以及权限控制

    相关知识点 不再对IdentityServer4做相关介绍,博客园上已经有人出了相关的系列文章,不了解的可以看一下: 蟋蟀大神的:小菜学习编程-IdentityServer4 晓晨Master:Ide ...

  10. C# linq左连接与分组

    1.左连接使用DefaultIfEmpty(): 2.分组时候判断newper.FirstOrDefault() == null ? null: newper.ToList()这个经常出错误,如果不判 ...