1

我可以在我的应用程序中REST API通过Feign但不能通过。RestTemplateSpring Boot

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

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

greeting-service能够毫无问题地向 Eureka 注册自己,并且我能够通过客户端使用该服务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.

GreetingClientApplication.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>
4

1 回答 1

3

在 GreetingClientApplication.java 中添加 @LoadBalanced ->

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}
于 2017-11-25T08:59:15.930 回答