1 添加redis maven依赖
<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>
2 添加redis配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
3 注入RedisTemplate
package com.example.demo.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author Aaron
* @date 2020/3/7
*/
@RestController
@RequestMapping("/redis")
public class RedisController {
@Resource
private RedisTemplate redisTemplate;
@GetMapping("add")
public String add(String key, String value) {
redisTemplate.opsForValue().set(key, value);
return "success";
}
@GetMapping("get")
public String get(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
}
4 测试
启动项目
访问url:http://localhost:8081/redis/add?key=a&value=123
访问url:http://localhost:8081/redis/get?key=a
扫描二维码关注公众号,回复:
14588207 查看本文章