第10讲 SpringBoot集成Redis

123 阅读1分钟

1、添加操作redis数据类型的依赖

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

2、在springboot核心配置文件中添加redis的配置

// 连接地址

spring.redis.host=192.168.1.2

// 连接密码

spring.redis.password=

spring.redis.port=6370

3、编写Controller

@RestController

public class RedisTestController {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @RequestMapping("redis/put/{key}/{value}")
    public String redisPut(@PathVariable("key") String key, @PathVariable("value") String value){
        System.out.println("key:"+key);
        System.out.println("value:"+value);
        redisTemplate.opsForValue().set(key, value);
        return "success";
    }

    @RequestMapping("redis/get/{key}")
    public String redisGet(@PathVariable("key") String key){
        String value = (String)redisTemplate.opsForValue().get(key);
        System.out.println(value);
        return value;
    }
}

4、启动测试

访问地址:http://localhost:8080/redis/put/aa/bb

redis中放了一个key为aa值为bb

获取redis中的值:http://localhost:8080/redis/get/aa