Simple FeignClient and RestTemplate example

1.controller deployed in eurka-server

spring.application.name=eurka-server

@RestController

public class CatController {

@PostMapping("/catname")

public String getCatName() {

return "BlueCat";

}

@PostMapping("/getcat")

public Cat getCat(String catName) {

System.out.println("This is from Eureka Server!");

Cat u = new Cat();

u.setName("lovely cat " + catName);

u.setAge(7);

u.setCardId("bc01");

return u;

}

@PostMapping("/addcat")

public Cat addCat(Cat cat) {

System.out.println("This is from Eureka Server in addCat!");

System.out.println(cat.getName());

cat.setName(cat + "--from server");

return cat;

}

@GetMapping("/svr")

public String frmEurekaSvr() {

return "This is from Eureka Server!";

}

@GetMapping("/svroo")

public Cat frmEurekaSvrOO(@RequestParam("catName") String catName) {

System.out.println("This is from Eureka Server!");

Cat u = new Cat();

u.setName("lovely cat " + catName);

return u;

}

}

2. 消费端的 feign client 定义,

@FeignClient("eurka-server")

public interface CatFeignInteface {

@PostMapping("/catname")

public String getName();

@PostMapping("/getcat")

public Cat getCatByName(String catName);

@PostMapping("/addcat")

public Cat addCat(Cat cat);

@GetMapping("/svr")

String hello();

@GetMapping("/svroo")

//without the @RequestParam, the request will be changed to PostMapping, then

//MethodNotAllowed Exception will be thrown

Cat helloOO(@RequestParam String catName);

}

3.  消费端的测试controller

import pojo.Cat;

@EnableFeignClients

@RestController

public class CatController {

@Autowired

CatFeignInteface cfi;

@Autowired

RestTemplate rest;

@PostMapping("/catname")

public String getName() {

return cfi.getName();

}

@PostMapping("/getcat")

public Cat getCatByName(String catName) {

return cfi.getCatByName(catName);

}

@PostMapping("/addcat")

public Cat addCat(Cat cat) {

return cfi.addCat(cat);

}

@PostMapping("/luck")

public String sayHello() {

return cfi.hello();

}

@PostMapping("/luckoo")

public Cat sayHelloOO(@RequestParam String catName) {

return cfi.helloOO(catName);

}

//without @LoadBalanced on bean

@PostMapping("/rtpgetcat")

public Cat getCatTmp(@RequestParam String catName) {

Cat cat = rest.getForObject("http://localhost:8761/svroo?catName=kkkkk?", Cat.class);

return cat;

}

//with @LoadBalanced on bean

@PostMapping("/rtpgetcatx")

public Cat getNamedCatTmp(@RequestParam String catName) {

Cat cat = new Cat();

cat.setName("luckyday");

cat.setAge("7");

cat.setCardId("zl8989");

return rest.postForObject("http://eurka-server/addcat", cat, Cat.class);

}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值