springBoot整合Redis(Jedis操作Redis)
    		       		warning:
    		            这篇文章距离上次修改已过424天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot整合Redis时,可以使用Jedis作为客户端。以下是一个简单的例子:
- 添加依赖到
pom.xml: 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>- 配置
application.properties或application.yml: 
# 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 org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
 
@RestController
public class RedisController {
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    @GetMapping("/set")
    public String setRedisWithSpring() {
        redisTemplate.opsForValue().set("key", "value");
        return "Data set with Spring";
    }
 
    @GetMapping("/get")
    public String getRedisWithSpring() {
        return (String) redisTemplate.opsForValue().get("key");
    }
 
    // 使用Jedis操作
    @Autowired
    private Jedis jedis;
 
    @GetMapping("/setJedis")
    public String setRedisWithJedis() {
        jedis.set("key", "value");
        return "Data set with Jedis";
    }
 
    @GetMapping("/getJedis")
    public String getRedisWithJedis() {
        return jedis.get("key");
    }
}在这个例子中,我们创建了一个简单的Spring Boot应用,使用@RestController提供两组接口,一组使用Spring的RedisTemplate进行操作,另一组使用Jedis客户端进行操作。
注意:在实际生产环境中,应该避免直接使用Jedis实例,因为它不支持多线程,应该使用JedisPool来管理Jedis实例的创建和销毁,以确保资源的有效管理和线程安全。
评论已关闭