provider
引用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置
spring:
application:
name: provider1
server:
port: 0 # 随机端口
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
instance-id: ${spring.application.name}:${random.int} # 如果端口随机,则必须设置
prefer-ip-address: true
启动
@SpringBootApplication
@EnableEurekaClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
提供服务
@RestController
public class ProController {
@RequestMapping("/hello")
public String index(@RequestParam String name) {
return "hello "+name+",this is first messge";
}
}
consumer
1、引用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、配置
spring:
application:
name: comsumer1
server:
port: 8886
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
3、启动
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
4、调用provider
必须添加:RequestParam
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("PROVIDER1")
public interface ProviderService {
@GetMapping("/hello")
public String hello(@RequestParam("name") String name);
}
controller正常调用即可:
@RestController
public class ConsumerController {
@Autowired
private ProviderService providerService;
@GetMapping("/hello")
public String hello(String name) {
return providerService.hello(name);
}
}