Spring Boot2.X 使用Lettuce连接Redis

本文介绍了Spring Boot2.x弃用Jedis转而使用Lettuce作为Redis客户端的原因,强调了Lettuce基于Netty的高性能特性。详细讲解了如何配置pom文件、配置redis、设置RestTemplateConfig、创建RedisTemplateUtil工具类以及在YML文件中的配置。此外,还展示了如何在应用启动时初始化Redis数据和在方法中注入并使用Lettuce的示例。
摘要由CSDN通过智能技术生成

前言

Spring Boot2.x 不再使用Jedis,换成了Lettuce。Lettuce是基于 Netty 实现的,所以性能更好。
1.pom文件

<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-pool2</artifactId>
           <version>2.5.0</version>
</dependency>

2.redis配置类

@Configuration
@AutoConfigureAfter(RedisConfiguration.class)
public class RedisConfiguration {
   
    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
   
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
}

3.RestTemplateConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
   
    @Bean
    //@LoadBalanced
    public RestTemplate restTemplate() {
   
        return new RestTemplate();
    }
}

4.RedisTemplateUtil

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @program: cabinet-meidi
 * @description: redis工具类
 * @author: cchan
 * @create: 2020年4月17
 **/

@Service
public class RedisTemplateUtil {
   

    private static final Logger LOG = LoggerFactory.getLogger(RedisTemplateUtil.class);

    //@Autowired
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
   
        this.redisTemplate = redisTemplate;
    }

    // =============================common============================
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间()
     * @return
     */
    public boolean expire(String key,
                          long time) {
   
        try {
   
            if (time > 0) {
   
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
   
            LOG.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间() 返回0代表为永久有效
     */
    public long getExpire(String key) {
   
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
   
        try {
   
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
   
            LOG.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
   
        if (key != null && key.length > 0) {
   
            if (key.length == 1) {
   
                redisTemplate.delete(key[0]);
            } else {
   
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    // ============================String=============================
    /**
     * 普通缓存获取
     * @param key 键
     * @return*/
    @SuppressWarnings({
   "unchecked", "static-access"})
    public <T> T get(String key, Class<T> clazz) {
   
        Object value = redisTemplate.opsForValue().get(key);

        if (value != null) {
   
            String temp;
            try {
   
                temp = new String();

                temp = temp.valueOf(value);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值