【Redis】Spring/SpringBoot 操作 Redis Java客户端

目录

  • [操作 Redis Java客户端](#操作 Redis Java客户端)
  • [SpringBoot 操作Redis 步骤](#SpringBoot 操作Redis 步骤)

操作 Redis Java客户端

1.Jedis

2.Lettuce(主流) <-Spring Data Redis

SpringBoot 操作Redis 步骤

1.添加Redis 驱动依赖

2.设置Redis 连接信息

java 复制代码
spring.redis.database=0
spring.redis.port=6379
spring.redis.host=127.0.0.1
# 可省略
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms

3.根据Redis API 操作Redis

java 复制代码
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class TestController {

    private final String _REDIS_KEY = "myapplication_test";

    // Spring Boot 自动装配机制
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/setval")
    public void setVal(String val) {
        redisTemplate.opsForValue() // 得到操作 redis 的类型
                .set(_REDIS_KEY, val,1000, TimeUnit.SECONDS);
    }
    @RequestMapping("/getval")
    public String getValue() {
        return (String) redisTemplate.opsForValue()
                .get(_REDIS_KEY);
    }
}
相关推荐
Seven9716 分钟前
【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
java·后端·设计模式
matrixlzp19 分钟前
Java 生成图形验证码
java·spring
冰淇淋@20 分钟前
HTTP发送POST请求的两种方式
java·spring boot·http
codingPower35 分钟前
IDEA接入阿里云百炼中免费的通义千问[2025版]
java·阿里云·intellij-idea
JouJz1 小时前
Java基础系列:深入解析反射机制与代理模式及避坑指南
java·开发语言·代理模式
小安同学iter1 小时前
Spring(七)AOP-代理模式
java·后端·spring
鸽鸽程序猿1 小时前
【JavaEE】SpringIoC与SpringDI
java·开发语言·java-ee
椰椰椰耶1 小时前
【redis】应用场景:缓存功能和计数功能
数据库·redis·缓存
Yuanymoon2 小时前
【由技及道】API契约的量子纠缠术:响应封装的十一维通信协议【人工智障AI2077的开发日志012】
java·架构设计·spirng
lucky1_1star2 小时前
FX-函数重载、重写(覆盖)、隐藏
java·c++·算法