springcloud服务消费者调用方式(rest 和 feign)

1、feign进行远程调用

      maven jar


  org.springframework.cloud
  spring-cloud-starter-feign

   实现调用服务接口

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

//调用注册的服务
@FeignClient(name="eureka-server")
public interface HelloRemote {

	 //restful api 调用
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name);
}

  启动类加上(basePackages服务接口所在的package)

@EnableFeignClients(basePackages="com.example.demo.remote")

  调用服务

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.example.demo.remote.HelloRemote;

@RestController
public class adfdController {
	
	@Autowired
	HelloRemote helloRemote;
	
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
    	
        return helloRemote.hello(name);
    	
    }   
    
    

}

2、rest 调用

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestTemplateConfig {
	
	@Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

   实现调用

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



@RestController
public class adfdController {
	
	
	@Autowired
    private RestTemplate restTemplate;
	
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
    	
    	return restTemplate.getForObject("http://eureka-server/hello/wewr", String.class);
    }   
    
    

}

 

你可能感兴趣的:(spring,cloud)