001/* 002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Florent Guillaume 016 */ 017package org.nuxeo.ecm.core.redis; 018 019import org.apache.commons.lang.StringUtils; 020import org.apache.commons.logging.Log; 021import org.apache.commons.logging.LogFactory; 022import org.nuxeo.common.xmap.annotation.XNode; 023import org.nuxeo.common.xmap.annotation.XObject; 024import org.nuxeo.ecm.core.api.NuxeoException; 025 026import redis.clients.jedis.Jedis; 027import redis.clients.jedis.JedisPool; 028import redis.clients.jedis.JedisPoolConfig; 029import redis.clients.jedis.Protocol; 030import redis.clients.jedis.exceptions.JedisException; 031 032/** 033 * Descriptor for a Redis configuration. 034 * 035 * @since 5.8 036 */ 037@XObject("server") 038public class RedisServerDescriptor extends RedisPoolDescriptor { 039 040 private static final Log log = LogFactory.getLog(RedisServerDescriptor.class); 041 042 @XNode("host") 043 public String host; 044 045 @XNode("port") 046 public int port = Protocol.DEFAULT_PORT; 047 048 protected boolean canConnect(String name, int port) { 049 try (Jedis jedis = new Jedis(name, port)) { 050 if (StringUtils.isNotBlank(password)) { 051 jedis.auth(password); 052 } 053 return canPing(jedis); 054 } 055 } 056 057 protected boolean canPing(Jedis jedis) { 058 try { 059 String pong = jedis.ping(); 060 return "PONG".equals(pong); 061 } catch (JedisException cause) { 062 log.debug("Exception during ping", cause); 063 return false; 064 } 065 } 066 067 @Override 068 public RedisExecutor newExecutor() { 069 if (!canConnect(host, port)) { 070 throw new NuxeoException("Cannot connect to Jedis host: " + host + ":" + port); 071 } 072 return new RedisPoolExecutor(new JedisPool(new JedisPoolConfig(), host, port, timeout, 073 StringUtils.defaultIfBlank(password, null), database)); 074 } 075 076}