spring cloud开发Greenwich版:服务调用RestTemplate(五)

建立注册服务器(ralab-server)并服务提供者(ralab-nlp)向其注册后,这时服务消费者(ralab-client,服务消费者也向注册服务器注册)可以通过访问注册服务器,查找服务实例名的方式查找服务提供者的相关信息,然后调用其服务

这里基于微服务’ralab-client’

  • Add @LoadBalanced to the RestTemplate Instance
  • Edit RestTemplate url parameter host as ‘nlp-service’

服务消费者ralab-client
RalabClientApplication文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.ralab.ralabclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class RalabClientApplication {

@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}

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

}

修改NlpResource文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ralab.ralabclient.resources;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/nlp")
public class NlpResource {

@Autowired
private RestTemplate restTemplate;

@GetMapping("/service")
public String index()
{
//String result = restTemplate.getForObject("http://localhost:8090/nlp/api", String.class);
String result = restTemplate.getForObject("http://nlp-service/nlp/api", String.class);
return result;
}
}

运行RalabClientApplication

测试http://localhost:8091/nlp/service

坚持原创技术分享,您的支持是我前进的动力!