springboot整合redis

71 阅读1分钟
  1. pom文件增加redis依赖
  2. 在test文件夹下,新建class,进行测试
  3. 本机安装redis,并启动
  4. 运行2个test方法,先存,再取。

pom文件增加redis依赖

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

在test文件夹下,新建class,进行测试

需要注意,增加test注解

package config;

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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSet(){
        redisTemplate.boundValueOps("name").set("zhangsan");
    }

    @Test
    public void testGet(){
        String name = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }

}

本机安装redis,并启动

我是mac os系统。打开终端。

brew install redis

等待,不用翻墙。安装完毕后,可以使用如下命令查看redis版本

redis-server --version

启动redis

redis-server

关闭 Ctrl+c