springboot基础五:集成redis

《springboot基础五:集成redis》要点:
本文介绍了springboot基础五:集成redis,希望对您有用。如果有疑问,可以联系我们。

springboot基础五:集成redis

前言

在项目里redis作为缓存已经是国际惯例了,那springboot项目里如何能与redis集成进行使用呢?照着教程做吧

配置

  1. 引入pom

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-redis</artifactId>

<version>1.4.7.RELEASE</version>

</dependency>

  1. 创建RedisUtil类

@Configuration

public class RedisUtil {

@Bean

public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory) {

RedisTemplate<Object,Object> template = new RedisTemplate<>();

template.setConnectionFactory(connectionFactory);

//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值

Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);

mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

serializer.setObjectMapper(mapper);

template.setValueSerializer(serializer);

//使用StringRedisSerializer来序列化和反序列化redis的key值

template.setKeySerializer(new StringRedisSerializer());

template.afterPropertiesSet();

return template;

}

}

  1. application.properties加入配置信息

## Redis 配置

## Redis数据库索引(默认为0)

spring.redis.database=0

## Redis服务器地址

spring.redis.host=127.0.0.1

## Redis服务器连接端口

spring.redis.port=6379

## Redis服务器连接暗码(默认为空)

spring.redis.password=

## 连接池最大连接数(使用负值表示没有限制)

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=0

  1. 使用:

    在需要的类里注入RedisTemplate即可

@Autowired

private RedisTemplate redisTemplate;

springboot配置redis真的是简单至极,赶紧本身试试吧!

欢迎参与《springboot基础五:集成redis》讨论,分享您的想法,编程之家PHP学院为您提供专业教程。

相关文章

今天小编给大家分享的是Springboot下使用Redis管道(pipeline...
本篇文章和大家了解一下springBoot项目常用目录有哪些。有一...
本篇文章和大家了解一下Springboot自带线程池怎么实现。有一...
这篇文章主要介绍了SpringBoot读取yml文件有哪几种方式,具有...
今天小编给大家分享的是SpringBoot配置Controller实现Web请求...
本篇文章和大家了解一下SpringBoot实现PDF添加水印的方法。有...