eureka注册中心:
@SpringBootApplication
@EnableEurekaServer
public class EurekaSerberApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaSerberApplication.class, args);
}
}
eureka配置文件:
spring.application.name=spring-cloud-eureka
server.port=1001
#表示是否将自己注册到Eureka Server,默认为true
eureka.client.register-with-eureka=false
#表示是否从Eureka Server获取注册信息,默认为true。
eureka.client.fetch-registry=false
#设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。
# 默认是http://localhost:8761/eureka ;多个地址可使用 , 分隔
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka
服务生产者:
配置文件:
spring.application.name=spring-cloud-producer
server.port=1002
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka
服务实现接口:
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index(@RequestParam String name) {
return "hello "+name+",this is 1 first messge";
}
@RequestMapping(value = "/haha" ,method = RequestMethod.POST)
public String haha(@RequestBody Greet greet) {
return "haha "+greet.getName()+",this is 1 first messge";
}
}
@SpringBootApplication
@EnableDiscoveryClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
服务消费者:
配置文件:
#在注册中心显示的app名称
spring.application.name=spring-cloud-consumer
server.port=1003
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka
启动类:
@SpringBootApplication
//启用服务注册与发现
@EnableDiscoveryClient
//:启用feign进行远程调用
@EnableFeignClients
public class EurekaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerApplication.class, args);
}
}
控制层:
@RestController
public class ConsumerController {
@Autowired
HelloRemote helloRemote;
@RequestMapping("/hello/{name}")
public String hello(@PathVariable("name") String name) {
return helloRemote.hello(name);
}
@RequestMapping("/hi")
public String hi(@RequestParam("name") String name) {
return helloRemote.hello(name);
}
@RequestMapping("/haha")
public String haha() {
return helloRemote.haha(new Greet("sasa"));
}
}
调用接口:
/**
* name:远程服务名,即spring.application.name配置的名称
此类中的方法和远程服务中contoller中的方法名和参数需保持一致
*/
@FeignClient(name= "spring-cloud-producer")
public interface HelloRemote {
//对应服务生产者中所提供的接口
@RequestMapping(value = "/hello")
public String hello(@RequestParam(value = "name") String name);
// @Headers({"Content-Type: application/json","Accept: application/json"})
@RequestMapping(value = "/haha",method = RequestMethod.POST)
public String haha(@RequestBody Greet greet);
}
Greet类:
public class Greet{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Greet(String name) {
this.name = name;
}
public Greet() {
}
}