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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ddl dml语句_用一句话介绍自己怎么介绍

    ddl dml语句_用一句话介绍自己怎么介绍数据库定义语言对数据库的操作对表的操作对字段,约束的操作DML语句表中数据增加,删除,修改总结提示:这里对文章进行总结:例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。…

    2022年10月19日
    2
  • tomcat jvm优化

    tomcat jvm优化tomcat经常挂机没反应,发现PSPermGen的使用率一直在99%。经常溢出优化如下:在bin/catalina.sh中添加 JAVA_OPTS=”-server-Xms800m-Xmx800m -XX:PermSize=64M-XX:MaxNewSize=256m-XX:MaxPermSize=128m-Djava.awt.headless=true”

    2022年6月12日
    29
  • Android开发入门案例「建议收藏」

    Android开发入门案例「建议收藏」初次接触安卓,做出来一个还能看的案例,类似小说阅读的APP,将源码记录一下一、案例效果1.登录界面2.注册界面3.用户信息显示界面4.小说阅读界面二、安卓代码1.AndroidManifest.xml<?xmlversion=”1.0″encoding=”utf-8″?><manifestxmlns:android=”http://schemas….

    2022年6月15日
    27
  • ItemDataBound里绑定数据

    ItemDataBound里绑定数据ItemDataBound里绑定数据DataRowViewdrv=(DataRowView)e.Item.DataItem;intUid=(int)drv[“UserID”];DataBinder.Eval(e.Item,”DataItem.PKIndex”);转载于:https://www.cnblogs.com/geoff/archive/2007/02/27/65…

    2022年10月8日
    2
  • linux系统怎么看内存使用率_cpu使用率0

    linux系统怎么看内存使用率_cpu使用率0一、查看CPU使用率1.top命令top命令可以看到总体的系统运行状态和cpu的使用率。%us:表示用户空间程序的cpu使用率(没有通过nice调度)%sy:表示系统空间的cpu使用率,主要是内核程序。%ni:表示用户空间且通过nice调度过的程序的cpu使用率。%id:空闲cpu%wa:cpu运行时在等待io的时间%hi:cpu处理硬中断的数量%si:cpu处理软中断…

    2025年8月29日
    5
  • 2021github仓库操作流程手册指南「建议收藏」

    2021github仓库操作流程手册指南「建议收藏」文章目录1.git操作2.git简介3.git安装4.git使用1.git初始化2.git设置用户信息3.git项目的拉取1.创建仓库2.本地初始化3.查看当前是否存在自己的账号信息并配置(包含步骤4)4.基础配置5.初始化内容6.开始引入自己的项目的地址7.更新操作8.git文件的添加保存和推送到github9.git文件的修改删除推送github10.gitpush操作每次都需要输入账号密码的解决办法5.总结至此git的仓库创建,仓库拉取到本地,文件的添加修改删除提交已经完成。其中遇到

    2022年7月16日
    19

发表回复

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

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