无法在 Spring Boot 中通过 RestTemplate 和 Eureka 使用 REST API

硝石

我能够AA消耗REST APIFeign,但不是通过RestTemplate我的Spring Boot应用程序。

我的项目中有以下 Maven 模块。

rest-client-sample (aggregator `pom` for the following child `maven` modules)
    eureka-server
    greeting-service
    greeting-client

greeting-service是能够与自己注册尤里卡没有任何问题,我能够通过消费服务Feign客户端。但是,当我添加代码以通过RestTemplate. 请参阅下面的屏幕截图。

在此处输入图片说明

服务器启动时出错(问候客户端)

2017-11-24 16:47:40.094  INFO 12700 --- [  restartedMain] c.e.demo.GreetingClientApplication       : No active profile set, falling back to default profiles: default
2017-11-24 16:47:40.121  INFO 12700 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45219d5a: startup date [Fri Nov 24 16:47:40 EST 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@5a56ca37
2017-11-24 16:47:41.710  INFO 12700 --- [  restartedMain] o.s.cloud.context.scope.GenericScope     : BeanFactory id=31702351-deb1-327c-b682-9744338df33c
2017-11-24 16:47:41.750  INFO 12700 --- [  restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-11-24 16:47:41.882  INFO 12700 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration' of type [org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration$$EnhancerBySpringCGLIB$$99e7b7a4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-24 16:47:41.904  INFO 12700 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$83d51460] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-24 16:47:43.188  INFO 12700 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 0 (http)
2017-11-24 16:47:43.217  INFO 12700 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-11-24 16:47:43.220  INFO 12700 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-24 16:47:43.552  INFO 12700 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-11-24 16:47:43.553  INFO 12700 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3431 ms
2017-11-24 16:47:44.187  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-24 16:47:44.196  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricsFilter' to: [/*]
2017-11-24 16:47:44.196  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-24 16:47:44.197  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-24 16:47:44.197  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-24 16:47:44.197  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-24 16:47:44.197  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2017-11-24 16:47:44.198  INFO 12700 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2017-11-24 16:47:44.310  INFO 12700 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@58eedc97: startup date [Fri Nov 24 16:47:44 EST 2017]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45219d5a
2017-11-24 16:47:44.414  INFO 12700 --- [  restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-11-24 16:47:44.940  WARN 12700 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'greetingClientApplication': Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.cloud.client.loadbalancer.LoadBalanced()}
2017-11-24 16:47:44.941  INFO 12700 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@58eedc97: startup date [Fri Nov 24 16:47:44 EST 2017]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45219d5a
2017-11-24 16:47:44.946  INFO 12700 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-11-24 16:47:44.988  INFO 12700 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-24 16:47:45.450 ERROR 12700 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field restTemplate in com.example.demo.GreetingClientApplication required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

问候客户应用程序.java

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@RestController
public class GreetingClientApplication {

    /* Consuming a service through Feign */
    @Autowired
    private GreetingClient greetingClient;

    @RequestMapping("/greetWFeign")
    public String greetWFeign() {
        return greetingClient.greetWorld();
    }

    /* Consuming a service through RestTemplate */
    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;
    private final String restUrl = "http://GREETING-SERVICE";

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @RequestMapping("/greetWRestTemplate")
    public String greetWRestTemplate() {
        return restTemplate.getForObject(restUrl, String.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(GreetingClientApplication.class, args);
    }

}

问候客户端/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>greeting-client</artifactId>
    <packaging>jar</packaging>
    <name>greeting-client</name>
    <description>A Feign-based client application that consumes greeting service (Eureka Client)</description>

    <parent>
        <groupId>com.example.demo</groupId>
        <artifactId>rest-client-sample</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>

</project>

问候客户端/application.yml

spring:
  application:
    name: greeting-client

# Use 0 for random port
server:
    port: 0 

eureka:
  client:
    serviceUrl:
      defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}
  instance:
    preferIpAddress: true

问候服务/pom.xml

    <modelVersion>4.0.0</modelVersion>
    <artifactId>greeting-service</artifactId>
    <packaging>jar</packaging>
    <name>greeting-service</name>
    <description>A REST-based greeting service (Eureka Client) which registers itself at the registry (Eureka Server)</description>

    <parent>
        <groupId>com.example.demo</groupId>
        <artifactId>rest-client-sample</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>

</project>

问候服务/application.yml

spring:
  application:
    name: greeting-service

# Use 0 for random port
server:
    port: 0 

eureka:
  client:
    serviceUrl:
      defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}
  instance:
    preferIpAddress: true

问候服务应用程序.java

@SpringBootApplication
@EnableEurekaClient
@RestController
public class GreetingServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GreetingServiceApplication.class, args);
    }

    @RequestMapping("/")
    public String greetWorld() {
        return "Hello World!";
    }

}   

尤里卡服务器/ pom.xml

    <modelVersion>4.0.0</modelVersion>
    <artifactId>eureka-server</artifactId>
    <packaging>jar</packaging>
    <name>eureka-server</name>
    <description>A service registry (Eureka Server)</description>

    <parent>
        <groupId>com.example.demo</groupId>
        <artifactId>rest-client-sample</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>   
    </dependencies>

EurekaServerApplication.java

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }

}

rest-client-sample/pom.xml(主聚合器 pom)

    <modules>
        <module>eureka-server</module>
        <module>greeting-service</module>
        <module>greeting-client</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath />
    </parent>

    <!-- Adding all the common dependencies here -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
格尼特·塞西

在 GreetingClientApplication.java 中添加 @LoadBalanced ->

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 java 和 spring boot 的 REST api

无法使用RestTemplate使用Rest API

在 @Async 方法中通过 Spring RestTemplate 调用 Rest API

如何使用Spring Boot和Spring Security保护REST API?

使用Spring Boot的Docker和Eureka无法注册客户端

无法使用 Spring RestTemplate 调用 Salesforce API

无法测试使用Spring Boot开发的REST API

使用Spring Boot和JWT保护REST Api

使用Spring Boot和RestTemplate使用嵌套的JSON数组

无法在 Spring Boot 中使用 JUnit 5 模拟 RestTemplate

使用restTemplate的功能区/ eureka / hystrix的spring-cloud无法设置连接/读取超时

使用 Spring-Boot 2.0.1 和 restTemplate 从 MongoDB ISODate 字段中检索数据

使用spring restTemplate的REST API的基本身份验证

使用 spring restTemplate 对 POST REST API 进行身份验证

无法使用Spring Cloud Consul和@EnableDiscoveryClient连接RestTemplate

使用Spring Security保护rest-api后,Spring Boot JS App无法正常工作

使用LDAP认证的Spring Boot REST API

使用Rest API 404的Spring Boot

使用Spring Boot使用Admin Rest API创建用户后无法登录Keycloak

无法使用 Spring Boot REST API 设置基本身份验证

Spring Boot RestTemplate setErrorHandler 和 Timeout 异常

Spring Boot REST API中的对象数组

Spring Boot应用程序中的Rest API无法在本地网络上访问

Spring Boot Rest API无法通过“ org.apache.catalina.LifecycleException:无法启动组件”在Tomcat 8.5.47上部署

我的Java Spring Boot Maven REST API无法正常工作

Spring-Boot REST API 无法解析 int 数组

无法使用RestTemplate解析REST响应

使用Spring和MongoDB的Rest API

在Spring Boot中何处放置调用REST API和修改实体的方法