java - Spring Boot Redis 配置不起作用

标签 java spring-boot redis

我正在开发一个带有 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 Boot 应用程序类中:

@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;

编辑 (2017-05-09) 我的理解是 Spring Boot Redis starter 假定默认值为 spring.redis.host=localhostspring.redis.port=6379,我还是把这两个加到 application.properties,但这并没有填补空白。

更新 (2017-05-10) 我对此线程添加了一个答案。

最佳答案

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

首先我在docker上安装了redis:

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

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

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 boot 应用程序和我的监听器:

@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=172.17.0.4

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

另外我用redis stat来监控redis。这是简单的监控。 enter image description here

关于java - Spring Boot Redis 配置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43879279/

相关文章:

java - Spring Boot 单页应用程序在任何 URL 上进行路由

mysql - 比较 ActiveRecord 结果并只使用不同的结果

javascript - Node Redis 获取高分的高效方式

java - 在 Java 中导入类

java - JAVA Swing 中的谷歌地图

java - 如何重构要从 React Native 调用的原生 Android Java 方法?

java - 如何检查Android应用程序是否进入前台?

java - 无法读取spring boot打包jar文件

php - 从 Predis 订阅函数中触发 Laravel 事件

java - Spring Boot/Data JPA EntityScan 递归