2024-09-02



// 在DolphinDB中使用Redis插件
 
// 首先,确保已经安装了Redis插件
 
// 连接到DolphinDB数据库
connect(HOST, USER, PASSWORD, DATABASE);
 
// 使用Redis插件
 
// 将DolphinDB表格数据保存到Redis
table = select * from loadTable("dfs://trades", `trades) where date >= 2021.01.01;
result = redis::saveTable(table, "trades", "localhost", 6379, "");
 
// 从Redis加载数据到DolphinDB表格
loadedTable = redis::loadTable("trades", "localhost", 6379, "");
 
// 将DolphinDB字典数据保存到Redis
dict = dict(1 2, "key1", "value1", "key2", "value2");
result = redis::saveDictionary(dict, "dict", "localhost", 6379, "");
 
// 从Redis加载字典数据到DolphinDB
loadedDict = redis::loadDictionary("dict", "localhost", 6379, "");

这段代码展示了如何在DolphinDB中使用Redis插件来进行数据的存储和检索。首先,它连接到了DolphinDB数据库,然后使用redis::saveTableredis::loadTable函数来操作表格数据。同时,它也演示了如何使用redis::saveDictionaryredis::loadDictionary来操作字典数据。这些操作都是基于已经安装好的Redis插件。

2024-09-02

在CentOS 7上部署Redis,可以按照以下步骤操作:

  1. 安装Redis



sudo yum install epel-release -y
sudo yum update -y
sudo yum install redis -y
  1. 启动Redis服务



sudo systemctl start redis
  1. 设置Redis开机自启



sudo systemctl enable redis
  1. 检查Redis是否正在运行



systemctl status redis
  1. (可选)配置Redis

    如果需要对Redis进行配置更改,可以编辑配置文件 /etc/redis.conf,然后重启Redis服务:




sudo systemctl restart redis
  1. (可选)设置Redis密码

    要设置Redis密码,请在/etc/redis.conf文件中找到以下行:




# requirepass foobared

去掉注释并更改"foobared"为你的密码:




requirepass your_password

然后重启Redis服务:




sudo systemctl restart redis

以上步骤将在CentOS 7上安装Redis,并确保它随系统启动。如果需要更高级的配置,可以编辑 /etc/redis.conf 文件。

2024-09-02

跳跃表(skiplist)是Redis中的一种数据结构,它允许快速的插入、删除、查找操作,在实现上是一种可以替代平衡树的数据结构,在查询速度上有可比的优势。

以下是一个简单的C语言实现的跳跃表节点和跳跃表结构的示例代码:




#include <stdlib.h>
 
// 跳跃表节点结构体
typedef struct skiplistNode {
    int key;
    struct skiplistNode *backward;
    struct skiplistNode *next[];
} skiplistNode;
 
// 跳跃表结构体
typedef struct skiplist {
    skiplistNode *header;
    int level;
} skiplist;
 
// 创建一个新的跳跃表节点
skiplistNode *createNode(int key, int level) {
    skiplistNode *node = malloc(sizeof(skiplistNode) + level * sizeof(skiplistNode*));
    node->key = key;
    node->backward = NULL;
    for(int i = 0; i < level; i++) {
        node->next[i] = NULL;
    }
    return node;
}
 
// 初始化一个跳跃表
skiplist *initSkipList() {
    skiplist *list = malloc(sizeof(skiplist));
    list->header = createNode(0, 32); // 假设最大层数为32
    list->header->backward = NULL;
    list->level = 0;
    return list;
}
 
// 插入一个新的节点到跳跃表
void insert(skiplist *list, int key) {
    skiplistNode *update[32];
    skiplistNode *node = list->header;
    int level = list->level;
 
    for(int i = level; i >= 0; i--) {
        while(node->next[i] && node->next[i]->key < key) {
            node = node->next[i];
        }
        update[i] = node;
    }
 
    if(node->next[0] && node->next[0]->key == key) {
        // 如果键值已存在,不做操作
    } else {
        int newLevel = randomLevel(); // 假设randomLevel函数用于生成新节点的层数
        if(newLevel > level) {
            for(int i = level + 1; i <= newLevel; i++) {
                update[i] = list->header;
            }
            level = newLevel;
        }
 
        skiplistNode *newNode = createNode(key, newLevel);
        for(int i = 0; i < newLevel; i++) {
            newNode->next[i] = update[i]->next[i];
            update[i]->next[i] = newNode;
 
            newNode->backward = update[i];
            if(newNode->next[i]) {
                newNode->next[i]->backward = newNode;
            }
        }
 
        if(level > list->level) {
            list->level = level;
        }
    }
}
 
// 查找一个节点
skiplistNode *search(skiplist *list, int key) {
    skiplistNode *node = list->header;
 
2024-09-02

在Spring Boot项目中引入Redis依赖,你需要在项目的pom.xml文件中添加Spring Data Redis和Jedis的依赖。以下是一个示例:




<dependencies>
    <!-- Spring Data Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
 
    <!-- Jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
 
    <!-- 其他依赖... -->
</dependencies>

添加依赖后,你需要在application.propertiesapplication.yml配置文件中配置Redis连接信息,例如:




# application.properties
spring.redis.host=localhost
spring.redis.port=6379

或者使用YAML格式:




# application.yml
spring:
  redis:
    host: localhost
    port: 6379

然后,你可以在你的Spring Boot应用中注入StringRedisTemplateRedisTemplate来使用Redis服务。例如:




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
 
@Component
public class RedisService {
 
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    public void setKeyValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }
 
    public String getValueByKey(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

以上代码展示了如何在Spring Boot应用中简单地使用Redis。

2024-09-02

在Spring Boot项目中使用MyBatis Plus和Redis实现二级缓存,你需要按照以下步骤操作:

  1. 引入相关依赖:



<!-- Spring Boot Starter Data Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- MyBatis Plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>你的版本号</version>
</dependency>
<!-- Redis Cache Starter -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-redis</artifactId>
    <version>你的版本号</version>
</dependency>
  1. 配置Redis和MyBatis缓存:



@Configuration
public class MyBatisConfig {
 
    @Bean
    public RedisCache redisCache(){
        return new RedisCache();
    }
 
    @Bean
    public Cache mybatisPlusRedisCache(RedisTemplate<String, Object> redisTemplate){
        return new MybatisPlusRedisCache(redisTemplate);
    }
}
  1. 在Mapper.xml中开启二级缓存并指定使用的缓存类型:



<mapper namespace="你的Mapper接口的全限定名">
  <cache type="org.mybatis.caches.redis.RedisCache"/>
  <!-- 你的SQL映射语句 -->
</mapper>
  1. 在application.properties或application.yml中配置Redis连接信息:



# Redis 配置
spring.redis.host=你的Redis服务器地址
spring.redis.port=你的Redis端口
spring.redis.password=你的Redis密码
spring.redis.database=你的Redis数据库索引
spring.redis.timeout=连接超时时间

以上步骤和配置足以在Spring Boot项目中启用MyBatis Plus的Redis二级缓存。记得替换示例代码中的占位符,并根据你的实际环境调整配置。

2024-09-02

Spring Boot整合Redis可以通过Spring Data Redis或Jedis实现。以下是使用Spring Data Redis的一个基本示例:

  1. 添加依赖到pom.xml



<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置application.propertiesapplication.yml



# application.properties
spring.redis.host=localhost
spring.redis.port=6379
  1. 使用RedisTemplateStringRedisTemplate操作Redis:



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
 
@RestController
public class RedisController {
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    @GetMapping("/set")
    public String setKey(@RequestParam String key, @RequestParam Object value) {
        redisTemplate.opsForValue().set(key, value);
        return "success";
    }
 
    @GetMapping("/get")
    public Object getKey(@RequestParam String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

这个示例提供了两个简单的API:一个用于设置键值对到Redis,另一个用于从Redis中获取键的值。在实际应用中,你可能需要根据具体需求进行更复杂的配置和编码。

2024-09-02



using StackExchange.Redis;
using System;
using System.Threading.Tasks;
 
public class RedisCacheService
{
    private readonly ConnectionMultiplexer _redisConnection;
    private readonly IDatabase _database;
 
    public RedisCacheService(string configuration)
    {
        _redisConnection = ConnectionMultiplexer.Connect(configuration);
        _database = _redisConnection.GetDatabase();
    }
 
    public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> getItem, TimeSpan expiry)
    {
        var redisKey = GetRedisKey(key);
        var item = await _database.StringGetAsync(redisKey);
 
        if (item.IsNullOrEmpty)
        {
            var value = await getItem();
            await _database.StringSetAsync(redisKey, JsonConvert.SerializeObject(value), expiry);
            return value;
        }
 
        return JsonConvert.DeserializeObject<T>(item);
    }
 
    private RedisKey GetRedisKey(string key)
    {
        return new RedisKey($"{typeof(T).Name}:{key}");
    }
}

这个代码实例展示了如何使用StackExchange.Redis库在.NET 6中实现一个简单的分布式缓存服务。GetOrSetAsync<T>方法尝试从Redis缓存中获取数据。如果缓存未命中,它会执行传入的getItem函数来获取数据,并将结果存储在Redis中,并设置指定的过期时间。这里使用了JsonConvert.SerializeObjectJsonConvert.DeserializeObject<T>来序列化和反序列化对象,需要添加对Newtonsoft.Json的引用。

2024-09-02

Redis 是一个开源的使用 C 语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库,并提供多种语言的 API。

基本部署

1. 下载和安装




# 下载
wget http://download.redis.io/releases/redis-6.2.6.tar.gz
# 解压
tar xzf redis-6.2.6.tar.gz
# 进入目录
cd redis-6.2.6
# 编译
make

2. 运行 Redis 服务器




# 运行
src/redis-server

3. 运行 Redis 客户端




# 新开一个终端,进入redis目录
# 运行
src/redis-cli
# 测试
ping

如果返回 PONG,则表示 Redis 安装成功并可以正常使用。

基本命令

1. 设置键值对




SET key value

2. 获取键对应的值




GET key

3. 删除键




DEL key

4. 检查键是否存在




EXISTS key

5. 设置键的过期时间




EXPIRE key seconds

6. 列出所有键




KEYS *

7. 获取键的数据类型




TYPE key

进阶应用

Redis 支持复杂的数据结构,如字符串、列表、集合、有序集合、哈希表等。

8. 使用列表(list)




# 在列表左侧插入元素
LPUSH key value
# 在列表右侧插入元素
RPUSH key value
# 获取列表指定范围内的元素
LRANGE key start stop

9. 使用集合(set)




# 添加成员
SADD key member
# 获取集合所有成员
SMEMBERS key

10. 使用有序集合(sorted set)




# 添加成员及其分数
ZADD key score member
# 获取有序集合范围内成员
ZRANGE key start stop

11. 使用哈希表




# 设置哈希表字段的值
HSET key field value
# 获取哈希表中字段的值
HGET key field
# 获取哈希表中所有字段及值
HGETALL key

持久化

Redis 支持两种持久化方式:RDB(默认)和 AOF。

12. RDB 持久化

定时将内存中的数据快照保存到磁盘的一个压缩二进制文件中。

13. AOF 持久化

记录每个写操作,将它们追加到文件中。

可以在 redis.conf 中配置持久化。

高级特性

14. 发布/订阅




# 发布消息
PUBLISH channel message
# 订阅频道
SUBSCRIBE channel

15. 事务




# 开启事务
MULTI
# 将多个命令入队到事务中
...
# 执行事务
EXEC

16. Lua 脚本




# 执行Lua脚本
EVAL script key
2024-09-02

Redis主从复制是一种可以让从服务器(replica)从主服务器(master)上复制数据的技术。

以下是一个基本的Redis主从复制的配置步骤:

  1. 在主服务器的redis.conf文件中,确保以下配置项被设置:



bind 0.0.0.0
port 6379
  1. 在从服务器的redis.conf文件中,确保以下配置项被设置:



bind 0.0.0.0
port 6380
  1. 在从服务器的redis.conf文件中,使用slaveof指令指定主服务器的IP和端口:



slaveof <master-ip> <master-port>

例如,如果主服务器的IP是192.168.1.100,端口是6379,从服务器的配置应该是:




slaveof 192.168.1.100 6379
  1. 启动主服务器和从服务器的Redis实例。

一旦配置完成并启动了Redis实例,主从复制将自动开始。从服务器会连接到主服务器,并开始接收来自主服务器的数据更新。

注意:在生产环境中,为了数据安全,建议设置密码验证来保护Redis实例,同时也可以考虑使用更复杂的配置,例如哨兵模式(Sentinel)或者集群模式(Cluster)来提供高可用性和数据分布。

2024-09-02

在Spring中配置Redis集群,你可以使用RedisClusterConfiguration类来设置集群的节点和其他属性。以下是一个配置Redis集群的示例:




import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
 
import java.util.HashSet;
import java.util.Set;
 
@Configuration
public class RedisClusterConfig {
 
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
        clusterConfig.setClusterNodes(new HashSet<>(Set.of(
                new RedisNode("127.0.0.1", 7000),
                new RedisNode("127.0.0.1", 7001),
                new RedisNode("127.0.0.1", 7002))));
        clusterConfig.setMaxRedirects(3);
 
        return new LettuceConnectionFactory(clusterConfig);
    }
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        return template;
    }
}

在这个配置中,我们定义了一个RedisClusterConfiguration实例,并通过setClusterNodes方法设置了集群节点的信息。RedisNodeRedisClusterConfiguration中的一个内部类,代表单个节点。Set.of是Java 9及以上版本的新特性,用于创建不可变集合。

maxRedirects属性设置了在集群环境中执行命令时,如果因为节点迁移导向新节点的最大重定向次数。

redisConnectionFactory方法返回一个LettuceConnectionFactory实例,它使用了我们配置好的集群配置。

redisTemplate方法返回一个RedisTemplate实例,它使用了刚才定义的LettuceConnectionFactory。这个模板可以用来操作Redis集群。