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

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 开启 MySQL 慢查询日志

    开启 MySQL 慢查询日志开启MySQL慢查询日志开启mysql的慢查询日志,可以记录查询超过指定时间的sql语句,可以方便更好的优化数据库系统的性能。一、参数说明slow_query_log:慢查询日志开启状态slow_query_log_file:慢查询日志存放位置long_query_time:查询超过多少秒才记录二、设置步骤1、查询相关参数配置mysql>showvariab…

  • 什么是有氧运动和无氧运动_SKU编码

    什么是有氧运动和无氧运动_SKU编码首先,搞清楚商品与单品的区别。例如,iphone是一个单品,但是在淘宝上当很多商家同时出售这个产品的时候,iphone就是一个商品了。商品:淘宝叫item,京东叫product,商品特指与商家有关的商品,每个商品有一个商家编码,每个商品下面有多个颜色,款式,可以有多个SKU。SPU=StandardProductUnit(标准化产品单元)SPU是商品信息聚合的最小单位,是一组可复用、易检…

  • 时间序列大数据平台建设经验谈

    时间序列大数据平台建设经验谈版权声明:本文由本人撰写并发表于2018年1月刊的《程序员》杂志,本文版权归《程序员》杂志所有,未经许可不得转载。引言在大数据的生态系统里,时间序列数据(TimeSeriesData,简称TSD)是很常见也是所占比例最大的一类数据,几乎出现在科学和工程的各个领域,一些常见的时间序列数据有:描述服务器运行状况的Metrics数据、各种IoT系统的终端数据、脑电图、汇率、股价、气象和天

  • 【Ubuntu 】Ubuntu 更换国内源—解决终端下载错误或速度慢的问题「建议收藏」

    【Ubuntu 】Ubuntu 更换国内源—解决终端下载错误或速度慢的问题「建议收藏」前言:安装好ubuntu双系统后,默认的软件更新源是国外的,在国内使用速度很慢,用”aptinstallxxx”安装软件时可能出现”网络不可达”、”你的网络需要认证吗”、”无法定位软件包”等错误,所以我们需要更换成国内的源,这样才能正常安装和更新软件。目录一、ubuntu16.04更换国内源二、ubuntu18.04更换国内源三、UbuntuROS更换国内源

  • 一次linux启动故障记录

    一次linux启动故障记录

  • c语言中(int)什么意思_c语言中怎么用int转化char

    c语言中(int)什么意思_c语言中怎么用int转化char1、int;int是C++关键字,表示整型,其大小是32位有符号整型,表示的范围是-2,147,483,648 到2,147,483,647;在声明和定义变量时使用,它表示的意思是所声明或所定义的变量为整型变量。如果其用于函数参数时,其传递方向为值传递,即只能将实参的值传递给形参,而不能将形参的值传递给实参。例如:通过这种方式去进行交换两个数是无法达到目的的。例子1:#include&…

发表回复

您的电子邮箱地址不会被公开。

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