java连接redis集群方式_redis java

java连接redis集群方式_redis javapackageorg.rx.util;importorg.redisson.Redisson;importorg.redisson.api.RedissonClient;importorg.redisson.config.Config;importorg.springframework.beans.factory.annotation.Autowired;im…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

package org.rx.util;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisShardInfo;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;

/**
 * Created by wangxiaoming on 2016/3/29.
 *
 * @author http://blog.csdn.net/java2000_wl
 */
@Component
public class RedisClient {
    private static RedissonClient redisson;

    //https://github.com/mrniko/redisson/wiki/8.-Distributed-locks-and-synchronizers
    public synchronized static RedissonClient getRedisson() {
        if (redisson == null) {

            Map<String, String> map = App.readSettings("app");
            Config config = new Config();
            config.useSingleServer().setAddress(String.format("%s:%s", map.get("redis.host"), map.get("redis.port")))
                    .setTimeout(App.convert(map.get("redis.timeout"), Integer.class));
            redisson = Redisson.create(config);
        }
        return redisson;
    }

    private static RedisTemplate<String, Object> Template;
    @Autowired
    private RedisTemplate<String, Object>        template;
    private String                               keyPrefix;

    public String getKeyPrefix() {
        return keyPrefix;
    }

    public void setKeyPrefix(String keyPrefix) {
        if (template != null) {
            throw new IllegalArgumentException("Autowired Instance");
        }
        this.keyPrefix = keyPrefix;
    }

    private RedisTemplate<String, Object> getTemplate() {
        if (template == null && Template == null) {
            Map<String, String> map = App.readSettings("app");
            JedisShardInfo config = new JedisShardInfo(map.get("redis.host"), Integer.parseInt(map.get("redis.port")));
            JedisConnectionFactory fac = new JedisConnectionFactory(config);
            fac.setTimeout(App.convert(map.get("redis.timeout"), Integer.class));
            fac.setUsePool(true);
            Template = new RedisTemplate<>();
            Template.setConnectionFactory(fac);
            Template.setKeySerializer(
                    new org.springframework.data.redis.serializer.StringRedisSerializer(Charset.forName("UTF8")));
            Template.setValueSerializer(
                    new org.springframework.data.redis.serializer.JdkSerializationRedisSerializer());
            Template.afterPropertiesSet();
        }
        return App.isNull(template, Template);
    }

    private byte[] getKeyBytes(String key) {
        try {
            key = App.isNull(keyPrefix, "") + key;
            return key.getBytes(App.UTF8);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public void set(String key, Object value) {
        this.set(key, value, 0L);
    }

    public void set(final String key, final Object value, final long liveTime) {
        getTemplate().execute(new RedisCallback() {
            public Long doInRedis(RedisConnection client) throws DataAccessException {
                byte[] theKey = getKeyBytes(key);
                client.set(theKey, App.serialize(value));
                if (liveTime > 0) {
                    client.expire(theKey, liveTime);
                }
                return 1L;
            }
        });
    }

    public Object get(final String key) {
        return getTemplate().execute(new RedisCallback() {
            public Object doInRedis(RedisConnection client) throws DataAccessException {
                byte[] theKey = getKeyBytes(key);
                byte[] theVal = client.get(theKey);
                if (theVal == null || theVal.length == 0) {
                    return null;
                }
                return App.deserialize(theVal);
            }
        });
    }

    public long del(final String... keys) {
        return (long) getTemplate().execute(new RedisCallback() {
            public Long doInRedis(RedisConnection client) throws DataAccessException {
                long result = 0;
                for (String key : keys) {
                    result += client.del(getKeyBytes(key));
                }
                return result;
            }
        });
    }

    public Set<String> keys(String pattern) {
        return getTemplate().keys(pattern);
    }

    public long dbSize() {
        return (long) getTemplate().execute(new RedisCallback<Object>() {
            public Long doInRedis(RedisConnection client) throws DataAccessException {
                return client.dbSize();
            }
        });
    }

    public boolean exists(final String key) {
        return (boolean) getTemplate().execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection client) throws DataAccessException {
                return client.exists(getKeyBytes(key));
            }
        });
    }

    public void flushDb() {
        getTemplate().execute(new RedisCallback() {
            public Object doInRedis(RedisConnection client) throws DataAccessException {
                client.flushDb();
                return null;
            }
        });
    }
}

  

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.5.0</version>
        </dependency>

 

转载于:https://www.cnblogs.com/Googler/p/7422489.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/182705.html原文链接:https://javaforall.net

(0)
上一篇 2022年10月12日 下午6:46
下一篇 2022年10月12日 下午6:46


相关推荐

  • Android下的配置管理之道之OpenGrok代码索引环境搭建[通俗易懂]

    Android下的配置管理之道之OpenGrok代码索引环境搭建[通俗易懂]1OpenGrok介绍OpenGrok是一个快速,便于使用的源码搜索引擎与对照引擎,它能够帮助我们快速的搜索、定位、对照代码树.接下来就具体讲解一下OpenGrok的安装及使用.2安装OpenGrok所需依赖RequirementsYouneedthefollowing:JDK1.8orhigherOpenGrok”’binar…

    2022年6月9日
    35
  • 美军打掉德国炮兵阵地的电影_英雄连2怎么找炮兵阵地

    美军打掉德国炮兵阵地的电影_英雄连2怎么找炮兵阵地司令部的将军们打算在 N×M 的网格地图上部署他们的炮兵部队。一个 N×M 的地图由 N 行 M 列组成,地图的每一格可能是山地(用 H 表示),也可能是平原(用 P 表示),如下图。在每一格平原地形上最多可以布置一支炮兵部队(山地上不能够部署炮兵部队);一支炮兵部队在地图上的攻击范围如图中黑色区域所示:如果在地图中的灰色所标识的平原上部署一支炮兵部队,则图中的黑色的网格表示它能够攻击到的区域:沿横向左右各两格,沿纵向上下各两格。图上其它白色网格均攻击不到。从图上可见炮兵的攻击范围不受地形的影响

    2022年8月9日
    8
  • 智谱宣布开源新一代旗舰大模型GLM-5 并宣布GLM Coding Plan涨价

    智谱宣布开源新一代旗舰大模型GLM-5 并宣布GLM Coding Plan涨价

    2026年3月12日
    2
  • java querystring_Request 对象之QueryString集合 | 学步园

    java querystring_Request 对象之QueryString集合 | 学步园QueryString 集合检索 HTTP 查询字符串中变量的值 HTTP 查询字符串由问号 后的值指定 几个不同的进程都可以生成查询字符串 如 anchor 标记 stringsample 生成值为 thisisasampl 的变量名字符串 通过发送表格或由用户在其浏览器的地址框中键入查询也可以生成查询字符串 语法 Request QueryString variable i

    2026年3月17日
    1
  • Qt核心机制与原理

    Qt核心机制与原理了解 Qt 和 C 的关系 掌握 Qt 的信号 槽机制的原理和使用方法 了解 Qt 的元对象系统 掌握 Qt 的架构 理解 Qt 的事件模型 掌握其使用的时机信号与槽 元对象系统 事件模型是 Qt 机制的核心 如果您想要掌握 Qt 编程 就需要对它们有比较深入的了解 本章重点介绍了信号与槽的基本概念和用法 元对象系统 Qt 的事件模型 以及它们在实际使用过程中应注意的一些问题 Qt 对标准 C 的扩展标准 C

    2026年3月16日
    2
  • 前端项目开发经验总结(持续更新)

    前端项目开发经验总结(持续更新)这篇博客是我在持续的开发以及维护项目中遇到的坑,并总结出做法,以备需要立项新项目需要注意的点。1.字符串一定能提到语言包中就提到语言包,不要贪图方便写死在代码中或者写死在美术资源中很多程序员喜欢贪图方便,在固定不变的字符串直接使用静态文本,代码中根本不去做控制,这样做一是不方便策划对于描述的一个更改,二是如果需要国际化,会造成很多不必要的工作。2.在存在字符串拼接的情况下…

    2026年4月13日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号