栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot Redis 集成配置详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot Redis 集成配置详解

spring Boot 熟悉后,集成一个外部扩展是一件很容易的事,集成Redis也很简单,看下面步骤配置:

一、添加pom依赖

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

二、创建 RedisClient.java

注意该类存放的package

package org.springframework.data.redis.connection.jedis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisException;


public class RedisClient {

  private static Logger logger = LoggerFactory.getLogger(RedisClient.class);

  private JedisConnectionFactory factory;

  public RedisClient(JedisConnectionFactory factory) {
    super();
    this.factory = factory;
  }

  
  public void putObject(final String key, final Object value, final int cacheSeconds) {
    if (StringUtils.isNotBlank(key)) {
      redisTemplete(key, new RedisExecute() {
 @Override
 public Object doInvoker(Jedis jedis) {
   try {
     jedis.setex(key.getBytes(Protocol.CHARSET), cacheSeconds, serialize(value));
   } catch (UnsupportedEncodingException e) {
   }

   return null;
 }
      });
    }
  }

  
  public Object getObject(final String key) {
    return redisTemplete(key, new RedisExecute() {
      @Override
      public Object doInvoker(Jedis jedis) {
 try {
   byte[] byteKey = key.getBytes(Protocol.CHARSET);
   byte[] bytevalue = jedis.get(byteKey);
   if (bytevalue != null) {
     return deserialize(bytevalue);
   }
 } catch (UnsupportedEncodingException e) {
   return null;
 }
 return null;
      }
    });
  }

  
  public String set(final String key, final String value, final int cacheSeconds) {
    return redisTemplete(key, new RedisExecute() {
      @Override
      public String doInvoker(Jedis jedis) {
 if (cacheSeconds == 0) {
   return jedis.set(key, value);
 }
 return jedis.setex(key, cacheSeconds, value);
      }
    });
  }

  
  public String get(final String key) {
    return redisTemplete(key, new RedisExecute() {
      @Override
      public String doInvoker(Jedis jedis) {
 String value = jedis.get(key);
 return StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
      }
    });
  }

  
  public long del(final String key) {
    return redisTemplete(key, new RedisExecute() {
      @Override
      public Long doInvoker(Jedis jedis) {
 return jedis.del(key);
      }
    });
  }

  
  public Jedis getResource() throws JedisException {
    Jedis jedis = null;
    try {
      jedis = factory.fetchJedisConnector();
    } catch (JedisException e) {
      logger.error("getResource.", e);
      returnBrokenResource(jedis);
      throw e;
    }
    return jedis;
  }

  
  public Jedis getJedis() throws JedisException {
    return getResource();
  }

  
  public void returnBrokenResource(Jedis jedis) {
    if (jedis != null) {
      jedis.close();
    }
  }

  
  public void returnResource(Jedis jedis) {
    if (jedis != null) {
      jedis.close();
    }
  }

  
  public  R redisTemplete(String key, RedisExecute execute) {
    Jedis jedis = null;
    try {
      jedis = getResource();
      if (jedis == null) {
 return null;
      }

      return execute.doInvoker(jedis);
    } catch (Exception e) {
      logger.error("operator redis api fail,{}", key, e);
    } finally {
      returnResource(jedis);
    }
    return null;
  }

  
  public static byte[] serialize(Object source) {
    ByteArrayOutputStream byteOut = null;
    ObjectOutputStream ObjOut = null;
    try {
      byteOut = new ByteArrayOutputStream();
      ObjOut = new ObjectOutputStream(byteOut);
      ObjOut.writeObject(source);
      ObjOut.flush();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
 if (null != ObjOut) {
   ObjOut.close();
 }
      } catch (IOException e) {
 ObjOut = null;
      }
    }
    return byteOut.toByteArray();
  }

  
  public static Object deserialize(byte[] source) {
    ObjectInputStream ObjIn = null;
    Object retVal = null;
    try {
      ByteArrayInputStream byteIn = new ByteArrayInputStream(source);
      ObjIn = new ObjectInputStream(byteIn);
      retVal = ObjIn.readObject();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (null != ObjIn) {
   ObjIn.close();
 }
      } catch (IOException e) {
 ObjIn = null;
      }
    }
    return retVal;
  }

  interface RedisExecute {
    T doInvoker(Jedis jedis);
  }
}



三、创建Redis配置类

RedisConfig.Java

package com.shanhy.example.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.RedisClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {

  @Bean
  public RedisTemplate redisTemplate(JedisConnectionFactory factory) {
    RedisTemplate template = new RedisTemplate();
    template.setConnectionFactory(factory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new RedisObjectSerializer());
    template.afterPropertiesSet();
    return template;
  }

  @Bean
  public RedisClient redisClient(JedisConnectionFactory factory){
    return new RedisClient(factory);
  }
}

RedisObjectSerializer.java

package com.shanhy.example.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;


public class RedisObjectSerializer implements RedisSerializer {

  private Converter serializer = new SerializingConverter();
  private Converter deserializer = new DeserializingConverter();

  static final byte[] EMPTY_ARRAY = new byte[0];

  @Override
  public Object deserialize(byte[] bytes) {
    if (isEmpty(bytes)) {
      return null;
    }

    try {
      return deserializer.convert(bytes);
    } catch (Exception ex) {
      throw new SerializationException("Cannot deserialize", ex);
    }
  }

  @Override
  public byte[] serialize(Object object) {
    if (object == null) {
      return EMPTY_ARRAY;
    }

    try {
      return serializer.convert(object);
    } catch (Exception ex) {
      return EMPTY_ARRAY;
    }
  }

  private boolean isEmpty(byte[] data) {
    return (data == null || data.length == 0);
  }

}



四、创建测试方法

下面代码随便放一个Controller里

  @Autowired
  private RedisTemplate redisTemplate;

  
  @RequestMapping("/redisTest")
  public String redisTest() {
    try {
      redisTemplate.opsForValue().set("test-key", "redis测试内容", 2, TimeUnit.SECONDS);// 缓存有效期2秒

      logger.info("从Redis中读取数据:" + redisTemplate.opsForValue().get("test-key").toString());

      TimeUnit.SECONDS.sleep(3);

      logger.info("等待3秒后尝试读取过期的数据:" + redisTemplate.opsForValue().get("test-key"));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    return "OK";
  }

五、配置文件配置Redis

application.yml

spring:
 # Redis配置
 redis:
  host: 192.168.1.101
  port: 6379
  password:
  # 连接超时时间(毫秒)
  timeout: 10000
  pool:
   max-idle: 20
   min-idle: 5
   max-active: 20
   max-wait: 2

这样就完成了Redis的配置,可以正常使用 redisTemplate 了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号