Spring Boot集成Redis
要在Spring Boot中集成Redis,你需要做以下几步:
- 添加Spring Data 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
中配置Redis连接。
# application.properties
spring.redis.host=localhost
spring.redis.port=6379
- 使用Spring Data Redis提供的
RedisTemplate
或StringRedisTemplate
来操作Redis。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setKeyValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValueByKey(String key) {
return redisTemplate.opsForValue().get(key);
}
}
- 在Spring Boot应用的主类或配置类中添加配置。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}
}
以上代码展示了如何在Spring Boot中配置和使用Redis。你可以通过RedisService
类来操作Redis,
评论已关闭