欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot Redis 集成配置详解

程序员文章站 2024-02-21 11:59:22
spring boot 熟悉后,集成一个外部扩展是一件很容易的事,集成redis也很简单,看下面步骤配置: 一、添加pom依赖

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

一、添加pom依赖

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-redis</artifactid>
    </dependency>

二、创建 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;

/**
 * 工具类 redisclient
 * 因为本类中获取jedispool调用的是jedisconnectionfactory中protected修饰的方法fetchjedisconnector()
 * 所以该类需要与jedisconnectionfactory在同一个package中
 *
 * @author 单红宇(csdn catoop)
 * @create 2017年4月9日
 */
public class redisclient {

  private static logger logger = loggerfactory.getlogger(redisclient.class);

  private jedisconnectionfactory factory;

  public redisclient(jedisconnectionfactory factory) {
    super();
    this.factory = factory;
  }

  /**
   * put操作(存储序列化对象)+ 生效时间
   * 
   * @param key
   * @param value
   * @return
   */
  public void putobject(final string key, final object value, final int cacheseconds) {
    if (stringutils.isnotblank(key)) {
      redistemplete(key, new redisexecute<object>() {
        @override
        public object doinvoker(jedis jedis) {
          try {
            jedis.setex(key.getbytes(protocol.charset), cacheseconds, serialize(value));
          } catch (unsupportedencodingexception e) {
          }

          return null;
        }
      });
    }
  }

  /**
   * get操作(获取序列化对象)
   * 
   * @param key
   * @return
   */
  public object getobject(final string key) {
    return redistemplete(key, new redisexecute<object>() {
      @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;
      }
    });
  }

  /**
   * setex操作
   * 
   * @param key
   *      键
   * @param value
   *      值
   * @param cacheseconds
   *      超时时间,0为不超时
   * @return
   */
  public string set(final string key, final string value, final int cacheseconds) {
    return redistemplete(key, new redisexecute<string>() {
      @override
      public string doinvoker(jedis jedis) {
        if (cacheseconds == 0) {
          return jedis.set(key, value);
        }
        return jedis.setex(key, cacheseconds, value);
      }
    });
  }

  /**
   * get操作
   * 
   * @param key
   *      键
   * @return 值
   */
  public string get(final string key) {
    return redistemplete(key, new redisexecute<string>() {
      @override
      public string doinvoker(jedis jedis) {
        string value = jedis.get(key);
        return stringutils.isnotblank(value) && !"nil".equalsignorecase(value) ? value : null;
      }
    });
  }

  /**
   * del操作
   * 
   * @param key
   *      键
   * @return
   */
  public long del(final string key) {
    return redistemplete(key, new redisexecute<long>() {
      @override
      public long doinvoker(jedis jedis) {
        return jedis.del(key);
      }
    });
  }

  /**
   * 获取资源
   * 
   * @return
   * @throws jedisexception
   */
  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;
  }

  /**
   * 获取资源
   * 
   * @return
   * @throws jedisexception
   */
  public jedis getjedis() throws jedisexception {
    return getresource();
  }

  /**
   * 归还资源
   * 
   * @param jedis
   * @param isbroken
   */
  public void returnbrokenresource(jedis jedis) {
    if (jedis != null) {
      jedis.close();
    }
  }

  /**
   * 释放资源
   * 
   * @param jedis
   * @param isbroken
   */
  public void returnresource(jedis jedis) {
    if (jedis != null) {
      jedis.close();
    }
  }

  /**
   * 操作jedis客户端模板
   * 
   * @param key
   * @param execute
   * @return
   */
  public <r> r redistemplete(string key, redisexecute<r> 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;
  }

  /**
   * 功能简述: 对实体bean进行序列化操作.
   * 
   * @param source
   *      待转换的实体
   * @return 转换之后的字节数组
   * @throws exception
   */
  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();
  }

  /**
   * 功能简述: 将字节数组反序列化为实体bean.
   * 
   * @param source
   *      需要进行反序列化的字节数组
   * @return 反序列化后的实体bean
   * @throws exception
   */
  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> {
    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;

/**
 * redis配置
 * 
 * @author 单红宇(csdn catoop)
 * @create 2016年9月12日
 */
@configuration
public class redisconfig {

  @bean
  public redistemplate<string, object> redistemplate(jedisconnectionfactory factory) {
    redistemplate<string, object> template = new redistemplate<string, object>();
    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;

/**
 * 实现对象的序列化接口
 * @author  单红宇(365384722)
 * @create  2017年4月9日
 */
public class redisobjectserializer implements redisserializer<object> {

  private converter<object, byte[]> serializer = new serializingconverter();
  private converter<byte[], object> 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<string, object> redistemplate;

  /**
   * 缓存测试
   *
   * @return
   * @author shanhy
   * @create 2016年9月12日
   */
  @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 了。

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