001/* 002 * (C) Copyright 2013 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 * Florent Guillaume 018 */ 019package org.nuxeo.ecm.core.redis; 020 021import org.apache.commons.lang.StringUtils; 022import org.apache.commons.logging.Log; 023import org.apache.commons.logging.LogFactory; 024import org.nuxeo.common.xmap.annotation.XNode; 025import org.nuxeo.common.xmap.annotation.XObject; 026import org.nuxeo.ecm.core.api.NuxeoException; 027 028import redis.clients.jedis.Jedis; 029import redis.clients.jedis.JedisPool; 030import redis.clients.jedis.JedisPoolConfig; 031import redis.clients.jedis.Protocol; 032import redis.clients.jedis.exceptions.JedisException; 033 034/** 035 * Descriptor for a Redis configuration. 036 * 037 * @since 5.8 038 */ 039@XObject("server") 040public class RedisServerDescriptor extends RedisPoolDescriptor { 041 042 private static final Log log = LogFactory.getLog(RedisServerDescriptor.class); 043 044 @XNode("host") 045 public String host; 046 047 @XNode("port") 048 public int port = Protocol.DEFAULT_PORT; 049 050 protected boolean canConnect(String name, int port) { 051 try (Jedis jedis = new Jedis(name, port)) { 052 if (StringUtils.isNotBlank(password)) { 053 jedis.auth(password); 054 } 055 return canPing(jedis); 056 } 057 } 058 059 protected boolean canPing(Jedis jedis) { 060 try { 061 String pong = jedis.ping(); 062 return "PONG".equals(pong); 063 } catch (JedisException cause) { 064 log.debug("Exception during ping", cause); 065 return false; 066 } 067 } 068 069 @Override 070 public RedisExecutor newExecutor() { 071 if (!canConnect(host, port)) { 072 throw new NuxeoException("Cannot connect to Jedis host: " + host + ":" + port); 073 } 074 return new RedisPoolExecutor(new JedisPool(new JedisPoolConfig(), host, port, timeout, 075 StringUtils.defaultIfBlank(password, null), database)); 076 } 077 078}