Redis是如今最火的缓存数据库之一,在springboot中经常有会使用到Redis,小伙伴们知道要如何在springboot中集成Redis吗?这次就一起来瞧瞧吧。
打开我们的springboot项目,直接配置:
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> < dependency > <groupId>org.springframework.boot</groupId> < artifactId > spring - boot - starter - data - redis < /artifactId> < /dependency> application.yml
application.yml
spring: redis: database: 0 host: 192.168 .1 .102 port: 6379 cache: type: redis
redis
package com.fooww.research.housesourcelist.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; /** * @author :zwy */ @Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { //对象的序列化 RedisSerializationContext.SerializationPair valueSerializationPair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()); //全局redis缓存过期时间 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1 L)) // .serializeKeysWith() .serializeValuesWith(valueSerializationPair); return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory), redisCacheConfiguration); } private Jackson2JsonRedisSerializer < Object > jackson2JsonRedisSerializer() { Jackson2JsonRedisSerializer < Object > jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer < > (Object.class); jackson2JsonRedisSerializer.setObjectMapper(objectMapper()); return jackson2JsonRedisSerializer; } private ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); return objectMapper; } }
启动类
@SpringBootApplication @EnableCaching public class HousesourcelistApplication { public static void main(String[] args) { SpringApplication.run(HousesourcelistApplication.class, args); } }
以上就是今天的全部内容,小伙伴们都理解了吗?如果还要了解更多java项目中常见问题及解决方法,请记得持续关注我们网站了解具体。
推荐阅读: