Redis 是一个开源的且使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库,并提供多种语言的 API。
它通常被称为数据结构服务器,因为值(value)可以是字符串(String), 哈希(Map), 列表(list), 集合(sets)和有序集合(sorted sets)等类型。
至于怎样在 Windows 和 Linux 安装和使用 Redis 这里将不再赘述。关于 Redis 的用法,读者可以自行参考 https://redis.io/documentation 官网。
笔者为了简单和方便,将使用 Windows 版本的 Redis。运行 redis-server.exe 去启动 Redis,如下:
redis-server.exe ./redis.windows.conf
Redis 启动结果:
_._ _.-``__ ''-._ _.-`` `. `_. ''-._ Redis 3.0.503 (00000000/0) 64 bit .-`` .-```. ```\/ _.,_ ''-._ ( ' , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379 | `-._ `._ / _.-' | PID: 10848 `-._ `-._ `-./ _.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | http://redis.io `-._ `-._`-.__.-'_.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | `-._ `-._`-.__.-'_.-' _.-' `-._ `-.__.-' _.-' `-._ _.-' `-.__.-' [10848] 30 Nov 12:38:02.783 # Server started, Redis version 3.0.503 [10848] 30 Nov 12:38:02.790 * DB loaded from disk: 0.001 seconds [10848] 30 Nov 12:38:02.790 * The server is now ready to accept connections on port 6379
在项目的 pom.xml 文件中添加如下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
在 resources/application.yml 文件中添加 Redis 配置,配置信息如下:
spring: # Redis配置 redis: # Redis数据库索引(默认为0) database: 0 # Redis主机地址 host: 127.0.0.1 # redis端口 port: 6379
使用 @Configuration 注解创建一个 RedisTemplate 实例,代码如下:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisTemplateConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 配置 Redis Template 序列化方式
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(redisSerializer);
        template.setValueSerializer(redisSerializer);
        template.setHashKeySerializer(redisSerializer);
        template.setHashValueSerializer(redisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}使用 RedisTemplate 进行对象存储时,需要使存储对象实现 Serializable 接口,这样才能够成功将对象进行序列化。
spring-data-redis 提供了多种 Serializer 策略,这对使用 jedis 的开发者而言,实在是非常便捷。spring-data-redis 提供了4种内置的 Serializer:
JdkSerializationRedisSerializer:使用 JDK 的序列化手段 (Serializable 接口,ObjectInputStrean,ObjectOutputStream),数据以字节流存储
StringRedisSerializer:字符串编码,数据以 String 存储
JacksonJsonRedisSerializer:json 格式存储
OxmSerializer:xml 格式存储
由于本实例仅仅用于演示,因此上面的实例将简单将字符串存储到 Redis,序列化对象使用 StringRedisSerializer。
由于前面已经创建了 RedisTemplate 实例,可以使用 @Autowired 注解注入 RedisTemplate 实例。代码如下:
import com.huangx.springboot.redis.services.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisServiceImpl {
    @Autowired
    private RedisTemplate redisTemplate;
    // 向 Redis 写入一个 KEY/VALUE
    @Override
    public void setValue(String key, String value) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
            throw new IllegalArgumentException("key或value不能为空");
        }
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(key, value);
    }
    // 从 Redis 获取指定 KEY 的值
    @Override
    public String getValue(String key) {
        if (StringUtils.isBlank(key)) {
            throw new IllegalArgumentException("key不能为空");
        }
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }
}到这里,Spring Boot 集成 Redis 完成了。
Spring Boot 集成 Redis 步骤如下:
(1)启动 Redis 服务
(2)创建一个 Spring Boot 项目,引入 Spring Boot Redis 依赖
(3)在 Spring Boot 中配置 Redis,如:Redis 主机地址、端口、密码等
(4)使用 @Configuration 注解创建 RedisTemplate 的实例
(5)使用 @Autowired 注解注入 RedisTemplate 的实例
(6)使用 RedisTemplate 实例向 Redis 写入/获取数据
