SpringBoot下连接Redis

我们都知道SpringBoot下利用@Autowired可以自动加载Spring容器中的类对象,但是今天在连接Redis时遇到了一些问题。

方法一:

1、构建Springboot的web工程

 

 

 

 2、构建好项目后在pom文件中添加依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

3、修改applacation.properties文件

spring.redis.database=0
spring.redis.cluster.nodes=#Redis地址及端口
spring.redis.password=#无密码则为空
spring.redis.timeout=60s
spring.redis.jedis.pool.min-idle=10
spring.redis.jedis.pool.max-idle=50
spring.redis.jedis.pool.max-wait=-1s
spring.redis.jedis.pool.max-active=-1

server.servlet.context-path=/test

4、编写controller层代码

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

@RestController
@RequestMapping("/test")
public class RedisController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/redisTest")
    public String redisTest(){
        stringRedisTemplate.opsForValue().set("qq","ww");
        return stringRedisTemplate.opsForValue().get("qq");
    }
}

注意这个controller类所在的包需要与springboot的启动类是同一级

 5、实现效果

 方法二:

1、创建SpringBoot的普通工程

其他步骤相同,选择创建nosql工程

 2、编写代码获取RedisTemplate

application.properties文件与上面相同

注意:在此我之前使用了两种错误的方法用@Autowired获取RedisTemplate对象,但是都是报空指针异常。

错误一:

利用JUnit4的@Test来测试是否获取到RedisTemplate,但是每次都是null,这个问题等有空解决后再补充。

错误二:

利用SpringBoot的启动类方法来执行redisTemplate操作,但是SpringBoot的启动类是利用main方法来执行的,是static的,所以要使用RedisTemplate的话就要用@Autowired来给静态的redisTemplate赋值,这是行不通的,静态属于类。

所以我后来是在项目的测试类中测试执行的,代码如下:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class Demo1ApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("key1","value1");
        System.out.println(redisTemplate.opsForValue().get("key1"));
    }

}

 

原文地址:https://www.cnblogs.com/pengpengdeyuan/p/12144781.html