Redis是一种基于内存的数据存储系统,它可以用作数据库、缓存、消息队列等多种用途。以下是Redis的一些基本使用方法:
安装Redis:可以从Redis的官方网站下载安装包并安装,或者使用包管理工具安装。
启动Redis:在终端中输入redis-server命令即可启动Redis服务器。如果没有指定配置文件,则会使用默认配置。
连接Redis:可以使用redis-cli命令来连接到Redis服务器。
存储和获取数据:可以使用Redis提供的set、get等命令来存储和获取数据。例如:
> set mykey "Hello Redis"
OK
> get mykey
"Hello Redis"
> set mykey "Hello Redis" EX 3600
OK
上述命令会将mykey的过期时间设置为3600秒。
6.数据类型:Redis支持多种数据类型,包括字符串、列表、集合、有序集合和哈希表等。可以根据不同的使用场景选择不同的数据类型。
7.发布和订阅消息:可以使用Redis提供的publish和subscribe命令来实现发布和订阅消息的功能。
8.集群:如果需要在多个Redis节点之间共享数据和负载均衡,可以使用Redis集群来实现。Redis集群可以自动将数据分配到不同的节点上,并支持故障转移和自动扩展等功能。
Redis是一个功能丰富的内存数据存储系统,提供了丰富的命令和方法来操作数据。以下是Redis中常用的方法:
这些是Redis中常用的方法,更详细的方法可以参考Redis的官方文档。
Redis支持多种数据类型,每种类型都有各自的特点和适用场景。以下是Redis中常用的数据类型:
字符串(string) 字符串是Redis中最基本的数据类型,可以存储任何类型的数据,例如文本、数字、二进制数据等。字符串类型支持的操作包括设置值、获取值、增加和减少值、设置过期时间等。
列表(list) 列表是一个有序的字符串列表,可以添加、删除、插入、查找和修改列表中的元素。列表类型支持的操作包括从列表的头部或尾部添加或删除元素、获取列表长度、获取指定范围的元素等。
集合(set) 集合是一组无序的唯一元素,支持添加、删除、查找元素等操作。集合类型支持的操作包括向集合中添加元素、从集合中删除元素、获取集合中的所有元素等。
有序集合(sorted set) 有序集合是一个有序的、唯一的元素列表,每个元素都关联了一个分值,支持按照分值排序和查询元素。有序集合类型支持的操作包括向有序集合中添加元素、根据分值获取指定范围的元素、根据成员获取元素的分值等。
哈希表(hash) 哈希表是一个键值对的集合,每个键都对应一个值。哈希表类型支持的操作包括添加、删除、获取、更新键值对等。
其他数据类型 Redis还支持其他一些数据类型,例如位图(bitmaps)、地理位置(geospatial)等。这些数据类型都有自己的特点和使用场景。
这些是Redis中常用的数据类型,每个数据类型都有自己的适用场景。根据具体的使用需求,可以选择不同的数据类型来存储数据。
在Spring Boot中使用Redis需要添加对应的依赖,然后配置Redis连接信息和RedisTemplate实例等。以下是使用Spring Boot连接Redis和操作Redis的示例代码:
在pom.xml文件中添加以下Redis相关的依赖:
org.springframework.boot spring-boot-starter-data-redis
在application.properties文件中添加Redis连接信息:
连接超时时间不能为空
spring.redis.host=localhost
spring.redis.port=6379
# redis访问密码(默认为空)
spring.redis.password=
# redis连接超时时间(单位为毫秒)
spring.redis.timeout=5000
在bootstrap.yml文件中添加Redis连接信息:
redis:# redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突database: 3# redis服务器地址(默认为localhost)host: localhost# redis端口(默认为6379)port: 6379# redis访问密码(默认为空)# password: # redis连接超时时间(单位为毫秒)timeout: 5000# redis连接池配置pool:# 最大可用连接数(默认为8,负数表示无限)max-active: 8# 最大空闲连接数(默认为8,负数表示无限)max-idle: 8# 最小空闲连接数(默认为0,该值只有为正数才有作用)min-idle: 0# 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限)max-wait: -1
第一种配置方式:
在配置类中配置RedisTemplate实例,可以选择使用默认的RedisTemplate实例或者自定义RedisTemplate实例,示例代码如下:
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());//初始化RedisTemplateredisTemplate.afterPropertiesSet();return redisTemplate;}
}
redisTemplate.afterPropertiesSet()说明:
redisTemplate.afterPropertiesSet()
是Spring Data Redis框架中的一个方法,用于配置和初始化一个RedisTemplate实例。
在 Spring 中,bean 通常是通过 XML 或 Java 配置文件创建和配置的。当 Spring 容器创建一个 bean 时,它会注入任何必要的依赖项,然后调用方法afterPropertiesSet()
让 bean 有机会执行任何额外的初始化任务。
对于 RedisTemplate,调用该afterPropertiesSet()
方法很重要,因为它设置了模板的连接工厂和 Redis 序列化程序。这些属性可以在 Spring 配置文件中或通过 RedisTemplate API 进行配置。
综上所述,调用redisTemplate.afterPropertiesSet()
是Spring Data Redis中初始化配置RedisTemplate实例的必要步骤。
RedisConnectionFactory说明:
RedisConnectionFactory 有几个实现,提供不同的方式来创建 Redis 连接,包括 LettuceConnectionFactory、JedisConnectionFactory 和 RedissonConnectionFactory。这些实现使用不同的 Redis 客户端库并提供不同的配置选项。
要在 Spring 应用程序中使用 RedisConnectionFactory,可以创建适当 RedisConnectionFactory 实现的 bean,并使用必要的 Redis 服务器连接详细信息(例如 Redis 主机和端口)对其进行配置。您还可以通过设置连接超时、池配置和 SSL 加密等选项来自定义连接工厂。
创建 RedisConnectionFactory bean 后,您可以使用它来创建 RedisTemplate 实例,方法是将其作为参数传递给 RedisTemplate 构造函数或通过方法进行设置setConnectionFactory
。RedisTemplate 提供了与 Redis 数据结构交互的便捷方法,例如哈希操作、列表操作和集合操作。
综上所述,RedisConnectionFactory 是 Spring Data Redis 提供的一个接口,定义了创建 Redis 连接的契约。它有几种实现,提供不同的方式来连接到 Redis 服务器,并且可以配置和定制以满足 Spring Redis 应用程序的要求。
第二种配置方式:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import javax.annotation.Resource;
import java.io.Serializable;@Configuration
public class RedisConfiguration {@Resourceprivate LettuceConnectionFactory myLettuceConnectionFactory;@Beanpublic RedisTemplate redisTemplate() {RedisTemplate template = new RedisTemplate<>();template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(myLettuceConnectionFactory);return template;}
}
LettuceConnectionFactory 说明:
LettuceConnectionFactory 是 Spring Data Redis 框架中的一个类,它提供了一个连接工厂,用于使用 Lettuce Redis 客户端库创建 Redis 连接。它实现了 RedisConnectionFactory 接口,可以与 RedisTemplate 一起使用以连接到 Redis 服务器并与之交互。
Lettuce 是一个用 Java 编写的高性能和可扩展的 Redis 客户端库。它支持连接池、线程安全和反应式编程等高级特性,使其成为高性能 Redis 应用程序的热门选择。
要在 Spring 应用程序中使用 LettuceConnectionFactory,首先需要创建一个 LettuceConnectionFactory 类型的 bean,并使用必要的 Redis 服务器连接详细信息(例如 Redis 主机和端口)对其进行配置。您还可以通过设置连接超时、池配置和 SSL 加密等选项来自定义连接工厂。
创建 LettuceConnectionFactory bean 后,可以使用它来创建 RedisTemplate 实例,方法是将其作为参数传递给 RedisTemplate 构造函数或通过方法进行设置setConnectionFactory
。RedisTemplate 提供了与 Redis 数据结构交互的便捷方法,例如哈希操作、列表操作和集合操作。
综上所述,LettuceConnectionFactory 是 Spring Data Redis 提供的连接工厂,它使用 Lettuce Redis 客户端库来创建 Redis 连接。它可以配置和定制以满足 Spring Redis 应用程序的要求。
在服务类中使用RedisTemplate实例操作Redis,以下是一个简单的示例代码:
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;@Component
public class RedisUtils {@Resourceprivate RedisTemplate redisTemplate;/*** 指定缓存失效时间* @param key 键* @param time 时间(秒)* @return*/public boolean expire(String key,long time){try {if(time>0){redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据key 获取过期时间* @param key 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key){return redisTemplate.getExpire(key,TimeUnit.SECONDS);}/*** 判断key是否存在* @param key 键* @return true 存在 false不存在*/public boolean hasKey(String key){try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除缓存* @param key 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String ... key){if(key!=null&&key.length>0){if(key.length==1){redisTemplate.delete(key[0]);}else{redisTemplate.delete(CollectionUtils.arrayToList(key));}}}//============================String=============================/*** 普通缓存获取* @param key 键* @return 值*/public Object get(String key){return key==null?null:redisTemplate.opsForValue().get(key);}/*** 普通缓存放入* @param key 键* @param value 值* @return true成功 false失败*/public boolean set(String key,Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间* @param key 键* @param value 值* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key,Object value,long time){try {if(time>0){redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);}else{set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 递增* @param key 键* @param delta 要增加几(大于0)* @return*/public long incr(String key, long delta){if(delta<0){throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减* @param key 键* @param delta 要减少几(小于0)* @return*/public long decr(String key, long delta){if(delta<0){throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}//================================Map=================================/*** HashGet* @param key 键 不能为null* @param item 项 不能为null* @return 值*/public Object hget(String key,String item){HashOperations operations =redisTemplate.opsForHash();List
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;import java.util.HashMap;
import java.util.Map;@ConditionalOnProperty(prefix="",name = "spring.redis.cluster", havingValue = "true")
public class RedisFactoryConfig {@Autowiredprivate Environment environment;@Beanpublic RedisConnectionFactory myLettuceConnectionFactory() {Map source = new HashMap();source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes"));
source.put("spring.redis.cluster.timeout", environment.getProperty("spring.redis.cluster.timeout"));source.put("spring.redis.cluster.timeout","5000");
// 配置集群的最大重定向次数source.put("spring.redis.cluster.max-redirects",
environment.getProperty("spring.redis.cluster.max-redirects"));RedisClusterConfiguration redisClusterConfiguration;redisClusterConfiguration = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));return new LettuceConnectionFactory(redisClusterConfiguration);}
}
@
ConditionalOnProperty说明:
@
ConditionalOnProperty是一个 Spring Framework 注释,允许开发人员根据应用程序环境中指定属性的存在或不存在,有条件地启用或禁用应用程序配置的某些部分。
此注释可用于根据一个或多个属性的值配置 bean、组件或整个配置类。例如,如果应用程序需要特定的数据库连接,但如果所需的属性不存在,它也可以回退到默认配置,则可用于@
ConditionalOnProperty根据设置的属性确定应使用哪个配置。
注释将一个或多个属性名称作为参数,以及这些属性的可选值。如果一个或多个属性存在于应用程序的环境中,并且它们的值与指定值(如果有)匹配,则带注释的组件或配置类将包含在应用程序的上下文中。否则,它将被排除在外。
@ConditionalOnProperty(prefix="",name = "spring.redis.cluster", havingValue = "true")具体说明:
@ConditionalOnProperty
是Spring框架提供的一个条件注解,它可以根据指定的属性值来决定是否需要创建一个Bean。具体来说,@ConditionalOnProperty
注解会检查指定的属性值,如果满足条件,则创建一个Bean;否则,不创建该Bean。
@ConditionalOnProperty
注解有三个主要的属性:
prefix
:属性的前缀。name
:属性的名称。havingValue
:属性的值。其中,prefix
和name
属性用于指定需要检查的属性,havingValue
属性用于指定需要检查的属性的值。
因此,@ConditionalOnProperty(prefix="",name = "spring.redis.cluster", havingValue = "true")
的意思是,当application.properties
配置文件中的spring.redis.cluster
属性值为true
时,才会创建被该注解标记的Bean。该注解中的prefix
属性为空,表示不需要前缀。
在Spring Boot中,@ConditionalOnProperty
注解经常用于根据配置文件中的属性值来创建Bean。例如,在配置Redis集群时,可以根据spring.redis.cluster
属性的值来决定是否创建一个连接池。如果spring.redis.cluster
为true
,则创建一个Redis集群连接池;否则,创建一个单节点Redis连接池。
先原理后代码,边学习边实践.原理用来指导代码阅读的聚焦点