Springboot中使用redis

springboot中使用redis

1.导入依赖

    //redis
    compile('org.apache.commons:commons-pool2:2.6.0')
    compile('org.springframework.boot:spring-boot-starter-data-redis:2.1.0.RELEASE')

2.配置 .properties 文件(单机或集群,这里采用单机)

################################ redis config begin  ##########################
#redis common config
spring.redis.password=
spring.redis.timeout=1000ms

#redis stand alone config
spring.redis.host=192.168.201.120
spring.redis.port=6379

#redis cluster nodes config
#spring.redis.cluster.nodes=192.168.201.120:6379
#spring.redis.lettuce.pool.min-idle=8
#spring.redis.lettuce.pool.max-idle=8
#spring.redis.lettuce.pool.max-active=32
################################ redis config   end  ##########################

3.编写RedisConfig类

package com.songzhen.howcool.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {

        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        //设置默认的Serialize,包含 keySerializer & valueSerializer
        redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        redisTemplate.setEnableTransactionSupport(false);
        return redisTemplate;
    }

}

4.在Service中引入RedisTemplate,并完成调用

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
           //redisTemplate.opsForValue().set("demoKey“, "demo", 30, TimeUnit.MINUTES);
        
posted @ 2019-03-11 13:54  青取之于蓝  阅读(170)  评论(0)    收藏  举报