繁体   English   中英

Spring 启动 Redis 配置不工作

[英]Spring Boot Redis configuration not working

我正在开发一个带有ServletInitializer的 Spring Boot [web] REST 风格的应用程序(因为它需要部署到现有的 Tomcat 服务器)。 它有一个@RestController ,其方法在调用时需要写入 Redis pub-sub channel 我有 Redis 服务器在本地主机上运行(默认端口,无密码)。 POM 文件的相关部分具有所需的入门依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

当我部署 WAR 并点击端点http://localhost:8080/springBootApp/health时,我得到以下响应:

{
  "status": "DOWN",
  "diskSpace": {
    "status": "UP",
    "total": 999324516352,
    "free": 691261681664,
    "threshold": 10485760
  },
  "redis": {
    "status": "DOWN",
    "error": "org.springframework.data.redis.RedisConnectionFailureException: java.net.SocketTimeoutException: Read timed out; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out"
  }
}

我将以下内容添加到我的 Spring 引导应用程序 class:

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    return new JedisConnectionFactory();
}

@Bean
public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
    template.setConnectionFactory(jedisConnectionFactory());
    return template;
}

在执行一些测试 Redis 代码之前,我还尝试将以下内容添加到我的@RestController中,但是我在堆栈跟踪中得到了与上面相同的错误:

@Autowired
private RedisTemplate<String, String> redisTemplate;

Edit (2017-05-09) My understanding is that Spring Boot Redis starter assumes the default values of spring.redis.host=localhost and spring.redis.port=6379 , I still added the two to application.properties , but that did not fill the gap .

更新(2017-05-10)我添加了这个线程的答案。

我用 redis 和 spring 引导做了一个简单的例子

首先我在 docker 上安装了 redis:

$ docker run --name some-redis -d redis redis-server --appendonly 是

然后我将此代码用于接收器:

import java.util.concurrent.CountDownLatch;

public class Receiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);

    private CountDownLatch latch;

    @Autowired
    public Receiver(CountDownLatch latch) {
        this.latch = latch;
    }

    public void receiveMessage(String message) {
        LOGGER.info("Received <" + message + ">");
        latch.countDown();
    }

}

这是我的 spring 启动应用程序和我的监听器:

@SpringBootApplication
// after add security library then it is need to use security configuration.
@ComponentScan("omid.spring.example.springexample.security")
public class RunSpring {
    private static final Logger LOGGER = LoggerFactory.getLogger(RunSpring.class);


    public  static   void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext contex =  SpringApplication.run(RunSpring.class, args);
    }

    @Autowired
    private ApplicationContext context;

    @RestController
    public class SimpleController{

        @RequestMapping("/test")
        public String getHelloWorld(){

            StringRedisTemplate template = context.getBean(StringRedisTemplate.class);
            CountDownLatch latch = context.getBean(CountDownLatch.class);

            LOGGER.info("Sending message...");

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0 ;  i < 100 ; i++) {
                        template.convertAndSend("chat", i + " => Hello from Redis!");
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }

                }
            });
            t.start();

            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            return "hello world 1";
        }
    }

    ///////////////////////////////////////////////////////////////


    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
}

重要的一点是 redis IP。如果你像我一样安装在 docker 那么你应该在 application.properties 中设置 ip 地址,如下所示: spring.redis.host=174.17.0.0

我把我所有的 spring 例子都放在github

另外我用redis stat监控了redis,很简单的监控。 在此处输入图像描述

您需要使用 application.properties 配置您的 redis 服务器信息:

# REDIS (RedisProperties)
spring.redis.cluster.nodes= # Comma-separated list of "host:port"
spring.redis.database=0 # Database index
spring.redis.url= # Connection URL, 
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.ssl=false # Enable SSL support.
spring.redis.port=6379 # Redis server port.

Spring数据文档: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html#REDIS

这是一个与代理相关的问题,甚至以某种方式限制了对 localhost 的访问。 一旦我禁用了代理设置, Redis health 是UP 这样问题就解决了。 我不必向application.properties添加任何属性,也不必在 Spring Boot 应用程序 class 中显式配置任何内容,因为 Spring Boot 和 Redis Starter 自动配置基于 Redis 默认值(适用于我的开发环境) . 我刚刚将以下内容添加到pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

以及@RestController的以下注释 class 和 Spring Boot 根据需要自动连接(太棒了。)。

@Autowired
private RedisTemplate<String, String> redisTemplate;

要向频道发布一条简单的消息,这一行代码足以验证设置:

this.redisTemplate.convertAndSend(channelName, "hello world");

我感谢所有评论,这些评论有助于支持我的支票。

Spring 数据 redis 属性已更新,例如spring.redis.host现在是spring.data.redis.host

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM