springboot 整合redis
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
如果你更喜欢Jedis的API,可以这样做:
添加依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
配置Redis:
# application.properties
spring.redis.host=localhost
spring.redis.port=6379
使用Jedis操作Redis:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;
@RestController
public class RedisController {
@Autowired
private Jedis jedis;
@GetMapping("/set")
public String setKey(@RequestParam String key, @RequestParam String value) {
jedis.set(key, value);
return "success";
}
@GetMapping("/get")
public String getKey(@RequestParam String key) {
return jedis.get(key);
}
}
注意:在实际生产环境中,你可能需要配置Redis连接池、密码、使用Lettuce代替Jedis等高级配置和优化措施。
评论已关闭