001/* 002 * (C) Copyright 2014-2015 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Thierry Delprat 018 * Florent Guillaume 019 */ 020package org.nuxeo.ecm.core.redis.contribs; 021 022import org.apache.commons.logging.Log; 023import org.apache.commons.logging.LogFactory; 024import org.nuxeo.ecm.core.api.NuxeoException; 025import org.nuxeo.ecm.core.redis.RedisAdmin; 026import org.nuxeo.ecm.core.redis.RedisExecutor; 027import org.nuxeo.ecm.core.uidgen.AbstractUIDSequencer; 028import org.nuxeo.runtime.api.Framework; 029 030import redis.clients.jedis.exceptions.JedisException; 031 032/** 033 * Redis-based UID generator. 034 * 035 * @since 7.4 036 */ 037public class RedisUIDSequencer extends AbstractUIDSequencer { 038 039 protected static final Log log = LogFactory.getLog(RedisUIDSequencer.class); 040 041 protected String namespace; 042 043 @Override 044 public void init() { 045 RedisAdmin redisAdmin = Framework.getService(RedisAdmin.class); 046 namespace = redisAdmin.namespace("counters"); 047 } 048 049 @Override 050 public void dispose() { 051 } 052 053 @Override 054 public void initSequence(String key, long id) { 055 RedisExecutor executor = Framework.getService(RedisExecutor.class); 056 try { 057 executor.execute(jedis -> jedis.set(namespace + key, String.valueOf(id))); 058 } catch (JedisException e) { 059 throw new NuxeoException(e); 060 } 061 } 062 063 @Override 064 public long getNextLong(String key) { 065 RedisExecutor executor = Framework.getService(RedisExecutor.class); 066 try { 067 return executor.execute(jedis -> jedis.incr(namespace + key)); 068 } catch (JedisException e) { 069 throw new NuxeoException(e); 070 } 071 } 072 073}