Spring Boot整合Redis可以通过Spring Data Redis或者Jedis两种方式实现。
- 使用Spring Data Redis
首先,添加依赖到你的pom.xml
文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
然后,在application.properties
或application.yml
中配置Redis连接:
# application.properties
spring.redis.host=localhost
spring.redis.port=6379
接下来,你可以使用RedisTemplate
或StringRedisTemplate
来操作Redis:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
@RestController
public class RedisController {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@GetMapping("/set")
public String setKey(@RequestParam String key, @RequestParam Object value) {
redisTemplate.opsForValue().set(key, value);
return "success";
}
@GetMapping("/get")
public Object getKey(@RequestParam String key) {
return redisTemplate.opsForValue().get(key);
}
}
- 使用Jedis
添加依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
配置Redis连接信息:
# application.properties
redis.host=localhost
redis.port=6379
使用Jedis操作Redis:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
@RestController
public class RedisController {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private int port;
@GetMapping("/set")
public String setKey(@RequestParam String key, @RequestParam String value) {
try (Jedis jedis = new Jedis(host, port)) {
jedis.set(key, value);
}
return "success";
}
@GetMapping("/get")
public String getKey(@RequestParam String key) {
try (Jedis jedis = new Jedis(host, port)) {
return jedis.get(key);
}
}
}
以上两种方式都可以实现Spring Boot整合Redis,你可以根据项目需求选择合适的方式。