Redis
1.安装
brew install redis
2.启动redis服务
brew services start redis
3.检查redis是否启动成功
brew services list/redis-cli ping
4.启动 Redis CLI(命令行客户端)
redis-cli
5.查看redis.conf文件(例如修改端口)
brew info redis
6.停止redis服务
brew services stop redis
进行基本的 Redis 操作
在 redis-cli 中输入以下命令可以执行一些基本操作:
-
存储键值对:
SET key "value"示例:
SET name "Alice" -
读取键的值:
GET key示例:
GET name这会返回
"Alice"。 -
删除键:
DEL key示例:
DEL name -
查看所有键:
KEYS * -
检查键是否存在:
EXISTS key示例:
EXISTS name
停止 Redis 服务
当不需要使用 Redis 时,可以通过以下命令停止服务:
brew services stop redis
重启 Redis 服务使配置生效:
brew services restart redis
示例:完整操作流程
-
启动 Redis 服务器:
brew services start redis -
打开 Redis 命令行:
redis-cli -
在
redis-cli中执行一些命令:SET favorite_color "blue" GET favorite_color # 应该返回 "blue" DEL favorite_color -
退出
redis-cli:exit -
停止 Redis 服务:
brew services stop redis
实操
set name myredis
get name
# 查询所有key值
keys *
# 模糊匹配key值
keys na*
使用GO语言测试
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"net/http"
)
var ctx = context.Background()
func main() {
// 创建 Redis 客户端
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379", // Redis 服务器地址
Password: "", // 密码,如果没有就留空
DB: 0, // 使用的数据库
})
// 测试连接
_, err := rdb.Ping(ctx).Result()
if err != nil {
panic(err)
}
fmt.Println("Connected to Redis")
router := gin.Default()
router.POST("/set", func(c *gin.Context) {
var json struct {
Key string `json:"key"`
Value string `json:"value"`
}
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := rdb.Set(ctx, json.Key, json.Value, 0).Err()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "set"})
})
router.GET("/get/:key", func(c *gin.Context) {
key := c.Param("key")
value, err := rdb.Get(ctx, key).Result()
if err == redis.Nil {
c.JSON(http.StatusNotFound, gin.H{"error": "key not found"})
} else if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusOK, gin.H{"key": key, "value": value})
}
})
// 启动服务器
router.Run(":8080")
}


Springboot整合Redis
使用Spring Data Redis 操作 Redis
redis
单线程,避免竞争
主从复制
Redis使用了IO多路复用技术来解决IO的问题


2815

被折叠的 条评论
为什么被折叠?



