一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術(shù)|正則表達(dá)式|

服務(wù)器之家 - 編程語言 - JAVA教程 - Spring Boot Redis 集成配置詳解

Spring Boot Redis 集成配置詳解

2020-09-30 15:34catoop JAVA教程

本篇文章主要介紹了Spring Boot Redis 集成配置詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

一、添加pom依賴

?
1
2
3
4
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

二、創(chuàng)建 RedisClient.java

注意該類存放的package

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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在同一個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;
  }
 
  /**
   * 功能簡述: 對實(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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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)對象的序列化接口
 * @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)建測試方法

下面代碼隨便放一個Controller里

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@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測試內(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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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 了。

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

原文鏈接:http://blog.csdn.net/catoop/article/details/71275331

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 射逼网站 | 亚洲国产精品成 | 日韩一品在线播放视频一品免费 | 亚洲精品www久久久久久久软件 | 亚洲不卡视频在线观看 | 亚洲精品久久中文字幕 | 97国产蝌蚪视频在线观看 | 国产精品亚欧美一区二区三区 | 久久久久久久久女黄 | 别停好爽好深好大好舒服视频 | 日韩av.com| 狠狠色婷婷丁香六月 | 久久er国产免费精品 | 欧美日韩国产超高清免费看片 | 无限资源在线观看高清 | 久久综合中文字幕佐佐木希 | 亚洲精品视频在线 | 欧美黑人ⅹxxx片 | 91亚洲专区 | 亚洲男人第一天堂 | 精品综合久久久久久88小说 | 欧洲第一区第二区第三区 | 日本三不卡 | bb18lv黑料正能量 | 8插8插 | 国产一卡二卡3卡4卡更新 | 免费老外的毛片清高 | 免费看www| 国产在线极品 | 爽好舒服使劲添高h视频 | 日本zzzzwww大片免费 | 亚洲国产精品无码中文在线 | 欧美日韩亚洲高清不卡一区二区三区 | 亚洲天堂网站 | 午夜无码片在线观看影院 | 日日日操 | 日本不卡不码高清免费观看 | 男女男在线精品网站免费观看 | 亚洲系列国产精品制服丝袜第 | juliaann大战两个黑人 | 日本一区二区三区精品 |