要在Spring Boot中集成Jedis,可以按照以下步驟進行實現:
pom.xml
文件中添加Jedis的依賴。<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
application.properties
或application.yml
文件中配置Redis的連接信息,如Redis的主機名、端口號、密碼等。spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(host);
configuration.setPort(port);
configuration.setPassword(password);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(configuration);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void delete(String key) {
redisTemplate.delete(key);
}
}
以上就是在Spring Boot中集成Jedis的簡單實現方式。通過配置Redis連接信息和使用RedisTemplate來操作Redis,可以方便地進行Redis的讀寫操作。