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.RedisCallable;
027import org.nuxeo.ecm.core.redis.RedisExecutor;
028import org.nuxeo.ecm.core.uidgen.AbstractUIDSequencer;
029import org.nuxeo.runtime.api.Framework;
030
031import redis.clients.jedis.Jedis;
032import redis.clients.jedis.exceptions.JedisException;
033
034/**
035 * Redis-based UID generator.
036 *
037 * @since 7.4
038 */
039public class RedisUIDSequencer extends AbstractUIDSequencer {
040
041    protected static final Log log = LogFactory.getLog(RedisUIDSequencer.class);
042
043    protected String namespace;
044
045    @Override
046    public void init() {
047        RedisAdmin redisAdmin = Framework.getService(RedisAdmin.class);
048        namespace = redisAdmin.namespace("counters");
049    }
050
051    @Override
052    public void dispose() {
053    }
054
055    @Override
056    public int getNext(String key) {
057        RedisExecutor executor = Framework.getService(RedisExecutor.class);
058        try {
059            return executor.execute(new RedisCallable<Long>() {
060                @Override
061                public Long call(Jedis jedis) {
062                    return jedis.incr(namespace + key);
063                }
064            }).intValue();
065        } catch (JedisException e) {
066            throw new NuxeoException(e);
067        }
068    }
069
070}