1
votes

redis.properties

#jedisPoolConfig
redis.minIdle=100
redis.maxIdle=500
redis.maxTotal=50000 
redis.maxWaitMillis=10000  
redis.testOnBorrow=true


#jedisPool
redis.host=192.168.13.169
redis.port=6379
redis.timeout=3000

redis.port2=6380

#redis-sentinel
redis.sentinel=192.168.13.169:26379
redis.master=mymaster

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--properties配置-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:redis.properties</value>
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

<!-- 连接池配置信息 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="${redis.maxIdle}" />
    <property name="maxTotal" value="${redis.maxTotal}" />
    <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
    <property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>

<!--初级版:单实例-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" scope="singleton">
    <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
    <constructor-arg name="host" value="${redis.host}" />
    <constructor-arg name="port" value="${redis.port}" type="int" />
</bean>

<!--主从-->
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
    <constructor-arg index="0" ref="jedisPoolConfig" />
    <constructor-arg index="1">
        <list>
            <bean class="redis.clients.jedis.JedisShardInfo">
                <constructor-arg name="host" value="${redis.host}" />
                <constructor-arg name="port" value="${redis.port}" />
                <constructor-arg name="timeout" value="${redis.timeout}" />
                <constructor-arg name="name" value="master" />
            </bean>
            <bean class="redis.clients.jedis.JedisShardInfo">
                <constructor-arg name="host" value="${redis.host}" />
                <constructor-arg name="port" value="${redis.port2}" />
                <constructor-arg name="timeout" value="${redis.timeout}" />
                <constructor-arg name="name" value="slave1" />
            </bean>
        </list>
    </constructor-arg>
</bean>

<!--sentinel模式-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
    <constructor-arg name="master" value="${redis.master}" />
    <constructor-arg name="sentinelHostAndPorts">
        <set>
            <value>${redis.sentinel}</value>
        </set>
    </constructor-arg>
</bean>

<!--Jedis连接池-->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true">
    <property name="hostName" value="${redis.host}"/>
    <constructor-arg ref="redisSentinelConfiguration" />
    <constructor-arg ref="jedisPoolConfig" />
</bean>

<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnFactory"/>

<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>

Code

Controller

@Controller
public class JedisController {
......
@Autowired
private RedisService redisService;
@RequestMapping(value = "test2")
@ResponseBody
public String test2(){
    redisService.set("key2","v2");
    return redisService.get("key1");
}
......
}

Service

@Service
public class RedisService extends BinaryRedisService {
public RedisService() {}

public String set(final String key, final String value) {
    return (String)this.execute(new Function<ShardedJedis, String>() {
        public String callBack(ShardedJedis shardedJedis) {
            return shardedJedis.set(key, value);
        }
    });
}
......
}

public class BinaryRedisService {
@Autowired
protected ShardedJedisPool shardedJedisPool;

public BinaryRedisService() {
}

protected <T> T execute(Function<ShardedJedis, T> fun) {
    ShardedJedis shardedJedis = null;
    T t = null;

    try {
        shardedJedis = this.shardedJedisPool.getResource();
        t = fun.callBack(shardedJedis);
    } catch (Exception var8) {
        var8.printStackTrace();
    } finally {
        if(null != shardedJedis) {
            shardedJedis.close();
        }

        return t;
    }
}
......
}

Problem

redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool at redis.clients.util.Pool.getResource(Pool.java:51) at redis.clients.jedis.ShardedJedisPool.getResource(ShardedJedisPool.java:36) at org.henry.service.BinaryRedisService.execute(BinaryRedisService.java:29) at org.henry.service.RedisService.set(RedisService.java:25) at org.henry.service.RedisService$$FastClassBySpringCGLIB$$f57afd3.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) at org.henry.service.RedisService$$EnhancerBySpringCGLIB$$d4e52321.set() at org.henry.controller.JedisController.test2(JedisController.java:51) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:524) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) at java.lang.Thread.run(Thread.java:745) Caused by: java.util.NoSuchElementException: Unable to validate object at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:506) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363) at redis.clients.util.Pool.getResource(Pool.java:49) ... 58 more

1

1 Answers

0
votes

You need to make sure that a) Redis is running b) that it is able to accept connections from remote hosts and c) if you have enabled password protection, provide a password in your code.

To make sure that it can accept connections from remote hosts you have to look at the redis.conf file. Find the line with the binding addresses (it should look something like: bind 127.0.0.1) and either comment it out (so it can accept requests from all remote hosts - not recommended for production, but it's OK for testing), or add the remote IPs you want your Redis service to accept connections from.