jedis例子

@Test public void testDiscoverNodesAutomatically(){
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort("127.0.0.1",7379));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  assertEquals(3,jc.getClusterNodes().size());
}
@Test public void testCalculateConnectionPerSlot(){
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort("127.0.0.1",7379));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  jc.set("foo","bar");
  jc.set("test","test");
  assertEquals("bar",node3.get("foo"));
  assertEquals("test",node2.get("test"));
}
@Test public void testRecalculateSlotsWhenMoved() throws InterruptedException {
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort("127.0.0.1",7379));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  int slot51=JedisClusterCRC16.getSlot("51");
  node2.clusterDelSlots(slot51);
  node3.clusterDelSlots(slot51);
  node3.clusterAddSlots(slot51);
  JedisClusterTestUtil.waitForClusterReady(node1,node2,node3);
  jc.set("51","foo");
  assertEquals("foo",jc.get("51"));
}
@Test public void testAskResponse() throws InterruptedException {
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort("127.0.0.1",7379));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  int slot51=JedisClusterCRC16.getSlot("51");
  node3.clusterSetSlotImporting(slot51,JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
  node2.clusterSetSlotMigrating(slot51,JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
  jc.set("51","foo");
  assertEquals("foo",jc.get("51"));
}
@Test(expected=JedisClusterException.class) public void testThrowExceptionWithoutKey(){
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort("127.0.0.1",7379));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  jc.ping();
}
@Test(expected=JedisClusterMaxRedirectionsException.class) public void testRedisClusterMaxRedirections(){
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort("127.0.0.1",7379));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  int slot51=JedisClusterCRC16.getSlot("51");
  node2.clusterSetSlotMigrating(slot51,JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
  jc.set("51","foo");
}
@Test public void testClusterCountKeysInSlot(){
  Set<HostAndPort> jedisClusterNode=new HashSet<HostAndPort>();
  jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(),nodeInfo1.getPort()));
  JedisCluster jc=new JedisCluster(jedisClusterNode);
  for (int index=0; index < 5; index++) {
    jc.set("foo{bar}" + index,"hello");
  }
  int slot=JedisClusterCRC16.getSlot("foo{bar}");
  assertEquals(5,node1.clusterCountKeysInSlot(slot).intValue());
}
private void setSuperConnectionHandler(JedisClusterConnectionHandler handler){
  try {
    Field connectionHandlerField=JedisCluster.class.getDeclaredField("connectionHandler");
    connectionHandlerField.setAccessible(true);
    connectionHandlerField.set(this,handler);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
/**
 * Store a job in Redis
 * @param jobDetail       the {@link JobDetail} object to be stored
 * @param replaceExisting if true, any existing job with the same group and name as the given job will be overwritten
 * @param jedis           a thread-safe Redis connection
 * @throws ObjectAlreadyExistsException
 */
@Override @SuppressWarnings("unchecked") public void storeJob(JobDetail jobDetail,boolean replaceExisting,JedisCluster jedis) throws ObjectAlreadyExistsException {
  final String jobHashKey=redisSchema.jobHashKey(jobDetail.getKey());
  final String jobDataMapHashKey=redisSchema.jobDataMapHashKey(jobDetail.getKey());
  final String jobGroupSetKey=redisSchema.jobGroupSetKey(jobDetail.getKey());
  if (!replaceExisting && jedis.exists(jobHashKey)) {
    throw new ObjectAlreadyExistsException(jobDetail);
  }
  jedis.hmset(jobHashKey,(Map<String,String>)mapper.convertValue(jobDetail,new TypeReference<HashMap<String,String>>(){
  }
));
  if (jobDetail.getJobDataMap() != null && !jobDetail.getJobDataMap().isEmpty()) {
    jedis.hmset(jobDataMapHashKey,getStringDataMap(jobDetail.getJobDataMap()));
  }
  jedis.sadd(redisSchema.jobsSet(),jobHashKey);
  jedis.sadd(redisSchema.jobGroupsSet(),jobGroupSetKey);
  jedis.sadd(jobGroupSetKey,jobHashKey);
}
/**
 * Remove the given job from Redis
 * @param jobKey the job to be removed
 * @param jedis  a thread-safe Redis connection
 * @return true if the job was removed; false if it did not exist
 */
@Override public boolean removeJob(JobKey jobKey,JedisCluster jedis) throws JobPersistenceException {
  final String jobHashKey=redisSchema.jobHashKey(jobKey);
  final String jobDataMapHashKey=redisSchema.jobDataMapHashKey(jobKey);
  final String jobGroupSetKey=redisSchema.jobGroupSetKey(jobKey);
  final String jobTriggerSetKey=redisSchema.jobTriggersSetKey(jobKey);
  Long delJobHashKeyResponse=jedis.del(jobHashKey);
  jedis.del(jobDataMapHashKey);
  jedis.srem(redisSchema.jobsSet(),jobHashKey);
  jedis.srem(jobGroupSetKey,jobHashKey);
  Set<String> jobTriggerSetResponse=jedis.smembers(jobTriggerSetKey);
  jedis.del(jobTriggerSetKey);
  Long jobGroupSetSizeResponse=jedis.scard(jobGroupSetKey);
  if (jobGroupSetSizeResponse == 0) {
    jedis.srem(redisSchema.jobGroupsSet(),jobGroupSetKey);
  }
  for (  String triggerHashKey : jobTriggerSetResponse) {
    final TriggerKey triggerKey=redisSchema.triggerKey(triggerHashKey);
    final String triggerGroupSetKey=redisSchema.triggerGroupSetKey(triggerKey);
    unsetTriggerState(triggerHashKey,jedis);
    jedis.srem(redisSchema.triggersSet(),triggerHashKey);
    jedis.srem(redisSchema.triggerGroupsSet(),triggerGroupSetKey);
    jedis.srem(triggerGroupSetKey,triggerHashKey);
    jedis.del(triggerHashKey);
  }
  return delJobHashKeyResponse == 1;
}
 
/**
 * Remove (delete) the <code> {@link Trigger}</code> with the given key.
 * @param triggerKey          the key of the trigger to be removed
 * @param removeNonDurableJob if true, the job associated with the given trigger will be removed if it is non-durableand has no other triggers
 * @param jedis               a thread-safe Redis connection
 * @return true if the trigger was found and removed
 */
@Override protected boolean removeTrigger(TriggerKey triggerKey,boolean removeNonDurableJob,JedisCluster jedis) throws JobPersistenceException, ClassNotFoundException {
  final String triggerHashKey=redisSchema.triggerHashKey(triggerKey);
  final String triggerGroupSetKey=redisSchema.triggerGroupSetKey(triggerKey);
  if (!jedis.exists(triggerHashKey)) {
    return false;
  }
  OperableTrigger trigger=retrieveTrigger(triggerKey,jedis);
  final String jobHashKey=redisSchema.jobHashKey(trigger.getJobKey());
  final String jobTriggerSetKey=redisSchema.jobTriggersSetKey(trigger.getJobKey());
  jedis.srem(redisSchema.triggersSet(),triggerHashKey);
  jedis.srem(triggerGroupSetKey,triggerHashKey);
  jedis.srem(jobTriggerSetKey,triggerHashKey);
  if (jedis.scard(triggerGroupSetKey) == 0) {
    jedis.srem(redisSchema.triggerGroupsSet(),triggerGroupSetKey);
  }
  if (removeNonDurableJob) {
    Long jobTriggerSetKeySizeResponse=jedis.scard(jobTriggerSetKey);
    Boolean jobExistsResponse=jedis.exists(jobHashKey);
    if (jobTriggerSetKeySizeResponse == 0 && jobExistsResponse) {
      JobDetail job=retrieveJob(trigger.getJobKey(),jedis);
      if (!job.isDurable()) {
        removeJob(job.getKey(),jedis);
        signaler.notifySchedulerListenersJobDeleted(job.getKey());
      }
    }
  }
  if (isNullOrEmpty(trigger.getCalendarName())) {
    jedis.srem(redisSchema.calendarTriggersSetKey(trigger.getCalendarName()),triggerHashKey);
  }
  unsetTriggerState(triggerHashKey,jedis);
  jedis.del(triggerHashKey);
  return true;
}
/**
 * Unsets the state of the given trigger key by removing the trigger from all trigger state sets.
 * @param triggerHashKey the redis key of the desired trigger hash
 * @param jedis          a thread-safe Redis connection
 * @return true if the trigger was removed, false if the trigger was stateless
 * @throws JobPersistenceException if the unset operation failed
 */
@Override public boolean unsetTriggerState(String triggerHashKey,JedisCluster jedis) throws JobPersistenceException {
  boolean removed=false;
  List<Long> responses=new ArrayList<>(RedisTriggerState.values().length);
  for (  RedisTriggerState state : RedisTriggerState.values()) {
    responses.add(jedis.zrem(redisSchema.triggerStateKey(state),triggerHashKey));
  }
  for (  Long response : responses) {
    removed=response == 1;
    if (removed) {
      jedis.del(redisSchema.triggerLockKey(redisSchema.triggerKey(triggerHashKey)));
      break;
    }
  }
  return removed;
}
 
/**
 * Store a  {@link Calendar}
 * @param name            the name of the calendar
 * @param calendar        the calendar object to be stored
 * @param replaceExisting if true, any existing calendar with the same name will be overwritten
 * @param updateTriggers  if true, any existing triggers associated with the calendar will be updated
 * @param jedis           a thread-safe Redis connection
 * @throws JobPersistenceException
 */
@Override public void storeCalendar(String name,Calendar calendar,boolean replaceExisting,boolean updateTriggers,JedisCluster jedis) throws JobPersistenceException {
  final String calendarHashKey=redisSchema.calendarHashKey(name);
  if (!replaceExisting && jedis.exists(calendarHashKey)) {
    throw new ObjectAlreadyExistsException(String.format("Calendar with key %s already exists.",calendarHashKey));
  }
  Map<String,String> calendarMap=new HashMap<>();
  calendarMap.put(CALENDAR_CLASS,calendar.getClass().getName());
  try {
    calendarMap.put(CALENDAR_JSON,mapper.writeValueAsString(calendar));
  }
 catch (  JsonProcessingException e) {
    throw new JobPersistenceException("Unable to serialize calendar.",e);
  }
  jedis.hmset(calendarHashKey,calendarMap);
  jedis.sadd(redisSchema.calendarsSet(),calendarHashKey);
  if (updateTriggers) {
    final String calendarTriggersSetKey=redisSchema.calendarTriggersSetKey(name);
    Set<String> triggerHashKeys=jedis.smembers(calendarTriggersSetKey);
    for (    String triggerHashKey : triggerHashKeys) {
      OperableTrigger trigger=retrieveTrigger(redisSchema.triggerKey(triggerHashKey),jedis);
      long removed=jedis.zrem(redisSchema.triggerStateKey(RedisTriggerState.WAITING),triggerHashKey);
      trigger.updateWithNewCalendar(calendar,misfireThreshold);
      if (removed == 1) {
        setTriggerState(RedisTriggerState.WAITING,(double)trigger.getNextFireTime().getTime(),triggerHashKey,jedis);
      }
    }
  }
}
 
/**
 * Remove (delete) the <code> {@link Calendar}</code> with the given name.
 * @param calendarName the name of the calendar to be removed
 * @param jedis        a thread-safe Redis connection
 * @return true if a calendar with the given name was found and removed
 */
@Override public boolean removeCalendar(String calendarName,JedisCluster jedis) throws JobPersistenceException {
  final String calendarTriggersSetKey=redisSchema.calendarTriggersSetKey(calendarName);
  if (jedis.scard(calendarTriggersSetKey) > 0) {
    throw new JobPersistenceException(String.format("There are triggers pointing to calendar %s, so it cannot be removed.",calendarName));
  }
  final String calendarHashKey=redisSchema.calendarHashKey(calendarName);
  Long deleteResponse=jedis.del(calendarHashKey);
  jedis.srem(redisSchema.calendarsSet(),calendarHashKey);
  return deleteResponse == 1;
}
 
/**
 * Get the keys of all of the <code> {@link Job}</code> s that have the given group name.
 * @param matcher the matcher with which to compare group names
 * @param jedis   a thread-safe Redis connection
 * @return the set of all JobKeys which have the given group name
 */
@Override public Set<JobKey> getJobKeys(GroupMatcher<JobKey> matcher,JedisCluster jedis){
  Set<JobKey> jobKeys=new HashSet<>();
  if (matcher.getCompareWithOperator() == StringMatcher.StringOperatorName.EQUALS) {
    final String jobGroupSetKey=redisSchema.jobGroupSetKey(new JobKey("",matcher.getCompareToValue()));
    final Set<String> jobs=jedis.smembers(jobGroupSetKey);
    if (jobs != null) {
      for (      final String job : jobs) {
        jobKeys.add(redisSchema.jobKey(job));
      }
    }
  }
 else {
    List<Set<String>> jobGroups=new ArrayList<>();
    for (    final String jobGroupSetKey : jedis.smembers(redisSchema.jobGroupsSet())) {
      if (matcher.getCompareWithOperator().evaluate(redisSchema.jobGroup(jobGroupSetKey),matcher.getCompareToValue())) {
        jobGroups.add(jedis.smembers(jobGroupSetKey));
      }
    }
    for (    Set<String> jobGroup : jobGroups) {
      if (jobGroup != null) {
        for (        final String job : jobGroup) {
          jobKeys.add(redisSchema.jobKey(job));
        }
      }
    }
  }
  return jobKeys;
}
时间: 2024-10-06 18:45:24

jedis例子的相关文章

利用Eclipse+maven编译Jedis源码成jar包和源码jar包

在GitHub上面,有很多源码都是maven项目,但是很多都没有jar包.去网上找到话第一个是比较难找,第二个是怕不够原汁原味.我们通过maven+Eclipse可以可视化将maven项目生成jar库包还有源码jar包. 1.下载maven 下载地址:http://maven.apache.org/download.html 2,解压 到本地: 3,配置环境变量 3-1,要先配置java-home变量. 新建系统变量,写入java-home值. 在系统变量的path里面添加  %JAVA_HOM

Jedis学习使用(java操作redis)

Jedis 是 Redis 官方首选的 Java 客户端开发包. 工作过程总结的一个示例,贴出来,如下: Java代码   package com.wujintao.redis; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.

Redis的Java客户端Jedis的八种调用方式(事务、管道、分布式)介绍

jedis是一个著名的key-value存储系统,而作为其官方推荐的java版客户端jedis也非常强大和稳定,支持事务.管道及有jedis自身实现的分布式. 在这里对jedis关于事务.管道和分布式的调用方式做一个简单的介绍和对比: 一.普通同步方式 最简单和基础的调用方式: 1 @Test 2 public void test1Normal() { 3 Jedis jedis = new Jedis("localhost"); 4 long start = System.curre

Jedis下的ShardedJedis(分布式)使用方法(二)

上一篇中介绍了ShardedJedis的基本使用方法以及演示了一个简单的例子,在这一篇中我们来介绍了ShardedJedis的原理. 1.获取数据过程 首先我们来看一下ShardedJedis的一个继承关系 看完了图,那么我们一步一步跟着我们的代码调用来看下,以我们最简单的 ShardedJedis.get()方法为例: 这边有调用一个getShard 方法,参数为我们传入的key,然后返回一个普通的jedis对象,那么这个getShard是用来做什么的呢,大家可能已经猜到了,这个方法就是会根据

Jedis操作Redis--Key操作

/** * Key(键) * DEL,DUMP,EXISTS,EXPIRE,EXPIREAT,KEYS,MIGRATE,MOVE,OBJECT,PERSIST,PEXPIRE,PEXPIREAT,PTTL,RANDOMKEY,RENAME,RENAMENX,RESTORE,SORT,TTL,TYPE,SCAN */ public class KeyTest { private Jedis jedis; private static final String KEY = "key"; p

Redis中sentinel集群的搭建和Jedis测试 图文教程[三]

在前两篇Redis中sentinel集群的搭建和Jedis测试 图文教程[一] 和Redis中sentinel集群的搭建和Jedis测试 图文教程[二] 中分别简述了Redis中sentinel集群的搭建和Java代码的Jedis测试. 这篇主要来简单分析一下Redis-sentinel集群的原理,根据追踪sentinel信息来完成Redis-sentinel集群测试中的详细的原理分析.包括master-slave各个中的sentinel信息的分析,failover过程,master宕机后的le

redis性能调优笔记(can not get Resource from jedis pool和jedis connect time out)

对这段时间redis性能调优做一个记录. 1.单进程单线程 redis是单进程单线程实现的,如果你没有特殊的配置,redis内部默认是FIFO排队,即你对redis的访问都是要在redis进行排队,先入先出的串行执行. 之所以能够保持高性能是因为以下3点: 1)内存操作 2)数据结构简单 3)大多数是hash操作 redis基本的命令耗时都是us级别的,所以及时是单进程单线程,也能保证很高的QPS. 2.can not get Resource from jedis pool和jedis con

关于jedis的使用小结

1.pom.xml中依赖如下:     <dependency>       <groupId>redis.clients</groupId>       <artifactId>jedis</artifactId>       <version>2.6.1</version>    </dependency> 2.jedis pool中ping的产生 线上storm的bolt使用jedis pool操作red

try redis(四) -java 客户端jedis 使用

不同的计算机语言针对redis,都有自己的客户端. 官网上也列出了客户端的 http://www.redis.io/clients java客户端如下: 感觉客户端无非也就是做些连接和拼接命令的事情.所以不费心思比较哪个好了,就选第一个吧.一般第一个应该都是不错的. 选择jedis ,发现他的代码是 GitHub 托管的,开源的.地址为 https://github.com/xetorthio/jedis 找到 maven dependency <dependency> <groupId