最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot Redis 集成配置詳解

 更新時(shí)間:2017年05月13日 16:56:18   作者:catoop  
本篇文章主要介紹了Spring Boot Redis 集成配置詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

spring Boot 熟悉后,集成一個(gè)外部擴(kuò)展是一件很容易的事,集成Redis也很簡單,看下面步驟配置:

一、添加pom依賴

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-redis</artifactId>
    </dependency>

二、創(chuàng)建 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
 * 因?yàn)楸绢愔蝎@取JedisPool調(diào)用的是JedisConnectionFactory中protected修飾的方法fetchJedisConnector()
 * 所以該類需要與JedisConnectionFactory在同一個(gè)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操作(存儲(chǔ)序列化對(duì)象)+ 生效時(shí)間
   * 
   * @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操作(獲取序列化對(duì)象)
   * 
   * @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
   *      超時(shí)時(shí)間,0為不超時(shí)
   * @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;
  }

  /**
   * 功能簡述: 對(duì)實(shí)體Bean進(jìn)行序列化操作.
   * 
   * @param source
   *      待轉(zhuǎn)換的實(shí)體
   * @return 轉(zhuǎn)換之后的字節(jié)數(shù)組
   * @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();
  }

  /**
   * 功能簡述: 將字節(jié)數(shù)組反序列化為實(shí)體Bean.
   * 
   * @param source
   *      需要進(jìn)行反序列化的字節(jié)數(shù)組
   * @return 反序列化后的實(shí)體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);
  }
}

三、創(chuàng)建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;

/**
 * 實(shí)現(xiàn)對(duì)象的序列化接口
 * @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);
  }

}

四、創(chuàng)建測(cè)試方法

下面代碼隨便放一個(gè)Controller里

  @Autowired
  private RedisTemplate<String, Object> redisTemplate;

  /**
   * 緩存測(cè)試
   *
   * @return
   * @author SHANHY
   * @create 2016年9月12日
   */
  @RequestMapping("/redisTest")
  public String redisTest() {
    try {
      redisTemplate.opsForValue().set("test-key", "redis測(cè)試內(nèi)容", 2, TimeUnit.SECONDS);// 緩存有效期2秒

      logger.info("從Redis中讀取數(shù)據(jù):" + redisTemplate.opsForValue().get("test-key").toString());

      TimeUnit.SECONDS.sleep(3);

      logger.info("等待3秒后嘗試讀取過期的數(shù)據(jù):" + 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:
  # 連接超時(shí)時(shí)間(毫秒)
  timeout: 10000
  pool:
   max-idle: 20
   min-idle: 5
   max-active: 20
   max-wait: 2

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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • springMVC詳細(xì)介紹

    springMVC詳細(xì)介紹

    下面小編就為大家?guī)硪黄赟pring MVC 詳細(xì)介紹。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2021-07-07
  • 存儲(chǔ)過程創(chuàng)建及springboot代碼調(diào)用存儲(chǔ)過程方式

    存儲(chǔ)過程創(chuàng)建及springboot代碼調(diào)用存儲(chǔ)過程方式

    文章介紹了如何在Navicat中創(chuàng)建存儲(chǔ)過程,并在Spring Boot項(xiàng)目中調(diào)用存儲(chǔ)過程,存儲(chǔ)過程創(chuàng)建步驟包括選擇函數(shù)類型、自定義函數(shù)名、添加參數(shù)等,在Spring Boot中調(diào)用存儲(chǔ)過程時(shí),可以通過JdbcTemplate或MyBatis等工具進(jìn)行
    2024-11-11
  • Java的invoke方法的具體使用

    Java的invoke方法的具體使用

    本文主要介紹了Java的invoke方法的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • Java文件操作之序列化與對(duì)象處理流詳解

    Java文件操作之序列化與對(duì)象處理流詳解

    這篇文章主要為大家詳細(xì)介紹了Java文件操作中的序列化與對(duì)象處理流,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-09-09
  • Springboot Mybatis Plus自動(dòng)生成工具類詳解代碼

    Springboot Mybatis Plus自動(dòng)生成工具類詳解代碼

    mybatis-plus 是一個(gè) Mybatis 的增強(qiáng)工具,在 Mybatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生,這篇文章帶你使用Springboot Mybatis Plus自動(dòng)生成工具類
    2021-11-11
  • mybatis某些字段無法映射成功的解決

    mybatis某些字段無法映射成功的解決

    這篇文章主要介紹了mybatis某些字段無法映射成功的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • SpringBoot Java后端實(shí)現(xiàn)okhttp3超時(shí)設(shè)置的方法實(shí)例

    SpringBoot Java后端實(shí)現(xiàn)okhttp3超時(shí)設(shè)置的方法實(shí)例

    Okhttp的使用沒有httpClient廣泛,網(wǎng)上關(guān)于Okhttp設(shè)置代理的方法很少,下面這篇文章主要給大家介紹了關(guān)于SpringBoot Java后端實(shí)現(xiàn)okhttp3超時(shí)設(shè)置的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • springboot接入deepseek深度求索代碼示例(java版)

    springboot接入deepseek深度求索代碼示例(java版)

    這篇文章主要介紹了springboot接入deepseek深度求索的相關(guān)資料,包括創(chuàng)建APIKey,封裝詢問工具方法,傳入問題,調(diào)用方法,但發(fā)現(xiàn)只能回答簡單問題,需要的朋友可以參考下
    2025-01-01
  • Spring cloud Feign 深度學(xué)習(xí)與應(yīng)用詳解

    Spring cloud Feign 深度學(xué)習(xí)與應(yīng)用詳解

    這篇文章主要介紹了Spring cloud Feign 深度學(xué)習(xí)與應(yīng)用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-06-06
  • 利用JavaFX工具構(gòu)建Reactive系統(tǒng)

    利用JavaFX工具構(gòu)建Reactive系統(tǒng)

    這篇文章主要介紹了使用JavaFX構(gòu)建Reactive系統(tǒng),利用JavaFX工具集中的新的超棒特性來構(gòu)建響應(yīng)式的快速應(yīng)用程序,感興趣的小伙伴們可以參考一下
    2016-02-02

最新評(píng)論

遂昌县| 玛沁县| 泰宁县| 曲周县| 普陀区| 巴彦县| 富蕴县| 闵行区| 松原市| 托克托县| 察隅县| 无棣县| 呼和浩特市| 塔城市| 五莲县| 定西市| 阳高县| 获嘉县| 紫阳县| 英超| 长岭县| 大方县| 双柏县| 边坝县| 德保县| 攀枝花市| 丽水市| 车致| 台前县| 邹平县| 南郑县| 灵川县| 洛阳市| 伊金霍洛旗| 科技| 兴和县| 塔城市| 永新县| 略阳县| 特克斯县| 宿迁市|