<h1>
<span class="link_title"><a href="/catoop/article/details/71275331">
Spring Boot Redis 集成配置 </a>
</span> </h1>
<div class="article_manage clearfix">

</div>    <style type="text/css">
.embody{
padding:10px 10px 10px;
margin:0 -20px;
border-bottom:solid 1px #ededed;
}
.embody_b{
margin:0 ;
padding:10px 0;
}
.embody .embody_t,.embody .embody_c{
display: inline-block;
margin-right:10px;
}
.embody_t{
font-size: 12px;
color:#999;
}
.embody_c{
font-size: 12px;
}
.embody_c img,.embody_c em{
display: inline-block;
vertical-align: middle;
}
.embody_c img{
width:30px;
height:30px;
}
.embody_c em{
margin: 0 20px 0 10px;
color:#333;
font-style: normal;
}
</style>
<script type="text/javascript">
$(function () {
try
{
var lib = eval("("+$("#lib").attr("value")+")");
var html = "";
if (lib.err == 0) {
$.each(lib.data, function (i) {
var obj = lib.data[i];
//html += '<img src="' + obj.logo + '"/>' + obj.name + "&nbsp;&nbsp;";
html += ' <a href="' + obj.url + '" target="_blank">';
html += ' <img src="' + obj.logo + '">';
html += ' <em><b>' + obj.name + '</b></em>';
html += ' </a>';
});
if (html != "") {
setTimeout(function () {
$("#lib").html(html);
$("#embody").show();
}, 100);
}
}
} catch (err)
{ } });
</script>

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)

* @myblog http://blog.csdn.net/catoop/

* @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 了。
<div class="readall_box csdn-tracking-statistics tracking-click readall_box_nobg" data-pid="blog" data-mod="popu_596" style="display: none;">
<div class="read_more_mask"></div>
<a class="btn btn-large btn-gray-fred read_more_btn" target="_self">阅读全文</a>
</div> <div class="csdn-tracking-statistics" data-pid="blog" data-mod="popu_222"><a href="javascript:void(0);" target="_blank">&nbsp;</a> </div>
<div class="csdn-tracking-statistics" data-pid="blog" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank">&nbsp;</a></div>
<script type="text/javascript">
function btndigga() {
$(".csdn-tracking-statistics[data-mod='popu_222'] a").click();
}
function btnburya() {
$(".csdn-tracking-statistics[data-mod='popu_223'] a").click();
}
</script> <div style="clear:both; height:10px;"></div>

Spring Boot Redis 集成配置(转)的更多相关文章

  1. Spring Boot Redis 集成 Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer'

    一.原因:redis集群环境没有开启Keyspace notifications 二.解决办法 @Configuration public class HttpSessionConfig { /** ...

  2. spring boot通过Spring Data Redis集成redis

    在spring boot中,默认集成的redis是Spring Data Redis,Spring Data Redis针对redis提供了非常方便的操作模版RedisTemplate idea中新建 ...

  3. spring boot redis 缓存(cache)集成

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  4. spring boot多数据源配置(mysql,redis,mongodb)实战

    使用Spring Boot Starter提升效率 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfi ...

  5. 【ELK】5.spring boot日志集成ELK,搭建日志系统

    阅读前必看: ELK在docker下搭建步骤 spring boot集成es,CRUD操作完整版 ============================================== 本章集成 ...

  6. 【转】spring boot application.properties 配置参数详情

    multipart multipart.enabled 开启上传支持(默认:true) multipart.file-size-threshold: 大于该值的文件会被写到磁盘上 multipart. ...

  7. Spring Boot 外部化配置(二) - @ConfigurationProperties 、@EnableConfigurationProperties

    目录 3.外部化配置的核心 3.2 @ConfigurationProperties 3.2.1 注册 Properties 配置类 3.2.2 绑定配置属性 3.1.3 ConfigurationP ...

  8. Spring Boot快速集成kaptcha生成验证码

    Kaptcha是一个非常实用的验证码生成工具,可以通过配置生成多样化的验证码,以图片的形式显示,从而无法进行复制粘贴:下面将详细介绍下Spring Boot快速集成kaptcha生成验证码的过程. 本 ...

  9. Spring Boot Redis 实现分布式锁,真香!!

    之前看很多人手写分布式锁,其实 Spring Boot 现在已经做的足够好了,开箱即用,支持主流的 Redis.Zookeeper 中间件,另外还支持 JDBC. 本篇栈长以 Redis 为例(这也是 ...

随机推荐

  1. thinkphp 组合查询

    组合查询的主体还是采用数组方式查询,只是加入了一些特殊的查询支持,包括字符串模式查询(_string).复合查询(_complex).请求字符串查询(_query),混合查询中的特殊查询每次查询只能定 ...

  2. Python-面向对象之高级进阶

    目录 classmethod与staticmethod 面向对象高级 isinstance.issubclass 反射 魔法方法(类内置方法) 单例模式 classmethod与staticmetho ...

  3. Django项目在linux上运行

    目录 前言 上传 解压 制作启动脚本 这是一篇关于如何在linux下,以后台进程的方式运行服务,命令改改基本上就通用了. 前言 我们在windows本地开发完Django项目后,需要把项目部署到lin ...

  4. 2019/10/24 CSP-S 模拟

    T1 tom 题意: 考虑一定是属于\(a\)的在一坨,属于\(b\)的在一坨,找到这条连接\(a\)和\(b\)的边,然后分别直接按\(dfs\)序染色即可 注意属于\(a\)的连通块或属于\(b\ ...

  5. [不知道出自什么OJ]最大利润

    题目描述 政府邀请了你在火车站开饭店,但不允许同时在两个相连接的火车站开.任意两个火车站有且只有一条路径,每个火车站最多有50个和它相连接的火车站. 告诉你每个火车站的利润,问你可以获得的最大利润为多 ...

  6. System.Text.Encoding.cs

    ylbtech-System.Text.Encoding.cs 1.程序集 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77 ...

  7. python中关于传递参数模块argprase的一些小坑

    今天在写代码的时候遇到了一个关于parser的一些小坑,记录在此备用. 我们知道在python中可以用argprase来传递一些参数给代码执行,来看下面的例子,假设现在有一个test文件夹,下面有3个 ...

  8. 转:如何成为Linux高手

    源地址:http://www.douban.com/note/60936243/ 经过几年的发展,公司在互联网公司里面也算是大公司了,线上机器使用的操作系统都是Linux,部门有几个同事,天天都跟Li ...

  9. Django项目: 项目环境搭建 ---- 三、在码云平台创建项目&推送到码云上

    三.在码云平台创建项目 git服务平台: 主要使用github(最主流) 国内访问速度慢 托管私有项目收费 国内一般使用码云gitee 国内访问速度快 托管私有项目免费(限制开发人数) 公司中使用gi ...

  10. 洛谷P3745 [六省联考2017]期末考试

    传送门 题解 //Achen #include<algorithm> #include<iostream> #include<cstring> #include&l ...