java Sping Boot Redis配置不起作用

enxuqcxy  于 2023-02-02  发布在  Java
关注(0)|答案(4)|浏览(179)

我正在用ServletInitializer开发一个Sping 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"
  }
}

我向Sping 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)我的理解是Sping Boot Redis启动器假设默认值为spring.redis.host=localhostspring.redis.port=6379,我仍然将这两个值添加到application.properties中,但这并没有填补差距。
更新(2017-05-10)我在此帖子中添加了一个答案。

qyuhtwio

qyuhtwio1#

我用redis和spring Boot 做了一个简单的例子
首先,我在Docker上安装了Redis:

$ docker运行--命名一些redis-d redis redis服务器--只附加是

然后,我用这个代码接收器:

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();
    }

}

这是我的Sping 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上,那么你应该在www.example.com中设置ip地址application.properties如下所示:spring.redis.host=172.17.0.4
我把所有的Spring示例都放在github here
此外,我还使用了redis stat来监视redis。这是一个简单的监视。x1c 0d1x

ve7v8dk2

ve7v8dk22#

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

# 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

iezvtpos

iezvtpos3#

这是一个与代理相关的问题,甚至连对localhost的访问都被限制了。一旦我禁用了代理设置,Redis的健康状况就是UP!所以问题就解决了。我不需要为application.properties添加任何属性,也不需要在Sping Boot 应用程序类中显式配置任何东西,因为Sping Boot 和Redis Starter会根据Redis的默认值自动配置(在我的开发环境中适用)。

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

并将以下代码添加到@RestController注解类,Sping Boot 根据需要自动连接(太棒了!)。

@Autowired
private RedisTemplate<String, String> redisTemplate;

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

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

我感谢所有的评论,这对备份我的支票很有帮助。

enyaitl3

enyaitl34#

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

相关问题