我遇到以下错误
org.springframework.data.redis.RedisConnectionFailureException:无法连接到Redis],根本原因
java.net.ConnectException:连接被拒绝
下面是我的代码
应用程序.属性
# Redis Configuration
spring.cache.type=redis
spring.redis.host=redis-14218.c301.ap-south-1-1.ec2.cloud.redislabs.com
spring.redis.port=14218
spring.redis.password=***
spring.redis.database=0
我的应用程序.Java
package com.serverless.serverlessapi;
import java.time.Duration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60))
.disableCachingNullValues()
.serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
@Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration("leads",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)))
.withCacheConfiguration("leadsCahce2",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)));
}
}
我的休息控制器
package com.serverless.serverlessapi.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.serverless.serverlessapi.services.LeadsService;
@RestController
@RequestMapping("/api")
public class LeadsRestController {
@Autowired
private LeadsService leadsService;
@Cacheable(value = "leads")
@GetMapping("/leads2")
public String getAllLeads2(@RequestParam(name = "limit") int limit, @RequestParam(name = "skip") int skip){
try {
return leadsService.getAllLeads2(limit,skip);
} catch (Exception e) {
e.printStackTrace();
}
return "data not found, please contact to admin";
}
}
检查springboot版本。如果是 3.x 版本,则 Redis 的配置属性已从 spring.redis 移出。到 spring.data.redis。因为 redis 自动配置需要 Spring Data 存在于类路径中。
spring:
data: # If 2.x then the data key is not needed
redis:
host: 127.0.0.1
port: 6379
password: 123456
database: 0
timeout: 3000