配置参数因为这篇文章不介绍 redis 集群的搭建,这里我们假设已经有了一个 redis 的集群环境,我们项目中需要调整以下几个部分
修改配置参数,集群的节点和密码配置;
确保引入的 jedis 版本支持设置密码,spring-data-redis 1.8 以上,springboot 1.5 以上才支持设置密码;
注入 redistemplate;
编写工具类;
修改配置参数############### redis 集群配置 #########################spring.custome.redis.cluster.nodes=172.20.0.1:7001,172.20.0.2:7002,172.20.0.3:7003spring.custome.redis.cluster.max-redirects=3spring.custome.redis.cluster.max-active=500spring.custome.redis.cluster.max-wait=-1spring.custome.redis.cluster.max-idle=500spring.custome.redis.cluster.min-idle=20spring.custome.redis.cluster.timeout=3000spring.custome.redis.cluster.password=redis.cluster.password
引入依赖(如果需要)确保 springboot 的版本大于 1.4.x 如果不是的话,采用如下配置,先排除 springboot 中旧版本 jedis 和 spring-data-redis,再依赖高版本的 jedis 和 spring-data-redis。
org.springframework.boot spring-boot-starter-data-redis redis.clients jedis org.springframework.data spring-data-redis redis.clients jedis 2.9.0 org.springframework.data spring-data-redis 1.8.0.release
注入 redistemplate注入 redistemplate 我们需要三个组件,分别是jedisconnectionfactory 、redisclusterconfiguration、jedispoolconfig,下面是注入redistempalte 的代码。先根据配置创建 jedisconnectfactory 同时需要配置 redisclusterconfiguration、jedispoolconfig,最后将jedisconnectionfactory 返回用于创建redistemplate
import com.fasterxml.jackson.annotation.jsonautodetect;import com.fasterxml.jackson.annotation.propertyaccessor;import com.fasterxml.jackson.databind.objectmapper;import org.apache.commons.pool2.impl.genericobjectpoolconfig;import org.springframework.beans.factory.annotation.value;import org.springframework.context.annotation.bean;import org.springframework.context.annotation.primary;import org.springframework.data.redis.connection.redisclusterconfiguration;import org.springframework.data.redis.connection.redisnode;import org.springframework.data.redis.connection.jedis.jedisclientconfiguration;import org.springframework.data.redis.connection.jedis.jedisconnectionfactory;import org.springframework.data.redis.core.redistemplate;import org.springframework.data.redis.serializer.jackson2jsonredisserializer;import org.springframework.data.redis.serializer.stringredisserializer;import java.time.duration;import java.util.arraylist;import java.util.list;public class redisclusterconfig { @bean(name = redistemplate) @primary public redistemplate redisclustertemplate(@value(${spring.custome.redis.cluster.nodes}) string host, @value(${spring.custome.redis.cluster.password}) string password, @value(${spring.custome.redis.cluster.timeout}) long timeout, @value(${spring.custome.redis.cluster.max-redirects}) int maxredirect, @value(${spring.custome.redis.cluster.max-active}) int maxactive, @value(${spring.custome.redis.cluster.max-wait}) int maxwait, @value(${spring.custome.redis.cluster.max-idle}) int maxidle, @value(${spring.custome.redis.cluster.min-idle}) int minidle) { jedisconnectionfactory connectionfactory = jedisclusterconnectionfactory(host, password, timeout, maxredirect, maxactive, maxwait, maxidle, minidle); return createredisclustertemplate(connectionfactory); } private jedisconnectionfactory jedisclusterconnectionfactory(string host, string password, long timeout, int maxredirect, int maxactive, int maxwait, int maxidle, int minidle) { redisclusterconfiguration redisclusterconfiguration = new redisclusterconfiguration(); list nodelist = new arraylist(); string[] cnodes = host.split(,); //分割出集群节点 for (string node : cnodes) { string[] hp = node.split(:); nodelist.add(new redisnode(hp[0], integer.parseint(hp[1]))); } redisclusterconfiguration.setclusternodes(nodelist); redisclusterconfiguration.setpassword(password); redisclusterconfiguration.setmaxredirects(maxredirect); // 连接池通用配置 genericobjectpoolconfig genericobjectpoolconfig = new genericobjectpoolconfig(); genericobjectpoolconfig.setmaxidle(maxidle); genericobjectpoolconfig.setmaxtotal(maxactive); genericobjectpoolconfig.setminidle(minidle); genericobjectpoolconfig.setmaxwaitmillis(maxwait); genericobjectpoolconfig.settestwhileidle(true); genericobjectpoolconfig.settimebetweenevictionrunsmillis(300000); jedisclientconfiguration.defaultjedisclientconfigurationbuilder builder = (jedisclientconfiguration.defaultjedisclientconfigurationbuilder) jedisclientconfiguration .builder(); builder.connecttimeout(duration.ofseconds(timeout)); builder.usepooling(); builder.poolconfig(genericobjectpoolconfig); jedisconnectionfactory connectionfactory = new jedisconnectionfactory(redisclusterconfiguration, builder.build()); // 连接池初始化 connectionfactory.afterpropertiesset(); return connectionfactory; } private redistemplate createredisclustertemplate(jedisconnectionfactory redisconnectionfactory) { redistemplate redistemplate = new redistemplate(); redistemplate.setconnectionfactory(redisconnectionfactory); jackson2jsonredisserializer<object> jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class); objectmapper om = new objectmapper(); om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any); om.enabledefaulttyping(objectmapper.defaulttyping.non_final); jackson2jsonredisserializer.setobjectmapper(om); stringredisserializer stringredisserializer = new stringredisserializer(); // key采用string的序列化方式 redistemplate.setkeyserializer(stringredisserializer); // hash的key也采用string的序列化方式 redistemplate.sethashkeyserializer(stringredisserializer); // value序列化方式采用jackson redistemplate.setvalueserializer(jackson2jsonredisserializer); // hash的value序列化方式采用jackson redistemplate.sethashvalueserializer(jackson2jsonredisserializer); redistemplate.afterpropertiesset(); return redistemplate; }}
编写工具类其实到这里基本上已经完成了,我们可以看到 springboot 项目接入 redis 集群还是比较简单的,而且如果之前单机环境就是采用redistemplate 的话,现在也就不需要编写工具类,之前的操作依旧有效。
/** * 删除key * @param key * @return */ public boolean delete(string key) { try { return gettemplate().delete(key); } catch (exception e) { log.error(redis haskey() is error); return false; } } /** * 普通缓存获取 * * @param key 键 * @return 值 */ public object get(string key) { return key == null ? null : gettemplate().opsforvalue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(string key, object value) { try { gettemplate().opsforvalue().set(key, value); return true; } catch (exception e) { log.error(redis set() is error); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(string key, object value, long time) { try { if (time > 0) { gettemplate().opsforvalue().set(key, value, time, timeunit.seconds); } else { set(key, value); } return true; } catch (exception e) { log.error(redis set() is error); return false; } } /** * 计数器 * * @param key 键 * @return 值 */ public long incr(string key) { return gettemplate().opsforvalue().increment(key); } public long incrby(string key, long step) { return gettemplate().opsforvalue().increment(key, step); } /** * hashget * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public object hget(string key, string item) { return gettemplate().opsforhash().get(key, item); } /** * 获取hashkey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public map hmget(string key) { return gettemplate().opsforhash().entries(key); } /** * 获取hashkey对应的批量键值 * @param key * @param values * @return */ public list<object> hmget(string key, list values) { return gettemplate().opsforhash().multiget(key, values); }
以上就是springboot项目如何接入redis集群的详细内容。