springboot基础五:集成redis

前言

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

配置

  1. 引入pom

          org.springframework.boot       spring-boot-starter-redis       1.4.7.RELEASE

  2. 创建RedisUtil类

    @Configurationpublic 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;    }}

  3. 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

  4. 使用: 
    在需要的类里注入RedisTemplate即可

    @Autowired    private RedisTemplate redisTemplate;

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

本文分享自微信公众号 - 架构师之屋(jiagoushizhiwu)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论

暂无评论