Spring Boot中Redis的简介
Redis(Remote Dictionary Server)是一个开源的使用ANSI C编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API,它通常被称为数据结构服务器,因为值可以是字符串、哈希表、列表、集合和有序集合。
在Spring Boot中使用Redis,我们可以通过添加依赖的方式来实现,首先需要在项目的pom.xml文件中添加spring-boot-starter-data-redis依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
Spring Boot中Redis的基本配置
1、在application.properties或application.yml文件中配置Redis的连接信息:
application.properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=your_password spring.redis.timeout=10000 spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.min-idle=0 spring.redis.jedis.pool.max-wait=-1
application.yml spring: redis: host: localhost port: 6379 password: your_password timeout: 10000 jedis: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1
2、在Java配置类中配置RedisTemplate:
@Configuration public class RedisConfig { @Bean("redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); template.setKeySerializer(stringRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
Spring Boot中使用Redis的操作示例
1、注入RedisTemplate对象:
@Autowired private RedisTemplate<String, Object> redisTemplate;
2、通过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); }
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/223933.html