springboot(四)集成redis

本文详细介绍了如何在SpringBoot项目中集成Redis,包括下载安装Redis、创建SpringBoot项目、添加相关依赖、配置属性文件、创建实体及实现缓存功能。通过访问特定URL,展示第一次访问存入Redis,第二次访问直接从Redis读取数据的运行效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.下载安装redis

https://blog.youkuaiyun.com/qq_42014192/article/details/88838597

2.新建一个springboot项目

https://blog.youkuaiyun.com/qq_42014192/article/details/88742559

3.添加redis相关依赖

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

4.application.properties文件中配置redis

# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

5.创建实体

public class User {
    private String name;
    private String pass;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public User() {
    }
}

6.自动根据方法生成缓存

package com.example.springboot_redis_demo.controller;

import com.example.springboot_redis_demo.been.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping("/getUser")
    @Cacheable(value="user-key")
    public User getUser() {
        User user=new User("aa@126.com", "aa");
        System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
        return user;
    }
}

7.启动springboot,访问http://localhost:8080/getUser

java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.example.springboot_redis_demo.been.User]

8.解决方案

https://blog.youkuaiyun.com/qq_42014192/article/details/88839621

9.运行结果:

第一次访问:进入controller将对象往redis数据库存入一份数据

第二次访问:无反应说明没有进入controller,直接从redis获取数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值