IDEA+Springboot 使用 Redis

IntelliJ IDEA 2022.1.3、Springboot 使用 Redis

目录结构及版本
在这里插入图片描述
在这里插入图片描述

1、本地下载redis,启动服务不要关

在这里插入图片描述

2、添加pm依赖
	<!--Redis依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
3、使用依赖jar包自带的RedisTemplate写一个RedisUtil工具类
package com.jeesite.modules.student.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {

    @Autowired
    RedisTemplate redisTemplate;

    public String getString(final String key) {
        return redisTemplate.opsForValue().get(key).toString();
    }

    public boolean setString(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

4、测试
package com.jeesite.modules.student;

import com.jeesite.modules.student.service.RedisUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class MyRedisTest {
    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void test() {
        Boolean flag = null;
        flag = redisUtil.setString("testRedisKey", "testRedisValue");

        System.out.println(flag);

        System.out.println(redisUtil.getString("testRedisKey"));

    }
}

在这里插入图片描述

可能的报错及解决办法:

1、报错:Could not autowire. No beans of ‘RedisUtil’ type found.
解决:@Autowired 换成 @Resource
2、报错:Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration
分析解决:启动时报这个错,原因是测试类所在包的目录结构与RedisUtil的不一致。测试类所在包目录结构与RedisUtil类的保持一致

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值