一竞漾、引入包
<!-- resis -->
<dependency>?
? ? <groupId>org.springframework.boot</groupId>?
? ? <artifactId>spring-boot-starter-redis</artifactId>?
? ? <version>RELEASE</version>
</dependency>
二拌消、配置文件
# REDIS (RedisProperties)
# Redis數(shù)據(jù)庫索引(默認為0)
spring.redis.database=0?
# Redis服務(wù)器地址
spring.redis.host=127.0.0.1
# Redis服務(wù)器連接端口
spring.redis.port=6379?
# Redis服務(wù)器連接密碼(默認為空)
spring.redis.password=123456
# 連接池最大連接數(shù)(使用負值表示沒有限制)
spring.redis.pool.max-active=8?
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1?
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8?
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0?
# 連接超時時間(毫秒)
# spring.redis.timeout=2000ms
三、配置類
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
public class RedisConfig{
? ? @Bean
? ? public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
? ? ? ? StringRedisTemplate template = new StringRedisTemplate(factory);
? ? ? ? Jackson2JsonRedisSerializer 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.setValueSerializer(jackson2JsonRedisSerializer);
? ? ? ? template.afterPropertiesSet();
? ? ? ? return template;
? ? }
}
四缎除、使用
@Cacheable(value="user-key",key = "'user'")
public BsideProduct getUser() {
BsideProduct bsideProduct = new BsideProduct();
bsideProduct.setProductNum(1);
bsideProduct.setProductName("bsideProduct1");
? ? return bsideProduct;
}