Springcloud (5)---feign service call
The previous article wrote a service call through the Ribbon, the other is the same, the only difference is to make a service call through feign.
Registration center and commodity microservices unchanged, as in the previous blog, specific reference: Springcloud (4)---Ribbon service call, source analysis
This way, only the order micro service is rewritten.
First, OrderService order micro-service1, Pom.xml
Here is the order Micro service for the previous article as soon as a new jar package is added
<!--Feign Dependency - <Dependency> <groupId>Org.springframework.cloud</groupId> <Artifactid>Spring-cloud-starter-openfeign</Artifactid> </Dependency>
2, Application.yml
Server: port:9001#Specify a registry address Eureka: client: serviceurl: defaultzone: http:localhost:7001/eureka/#name of the service Spring: application: name: Order-Service#Custom load balancing policies (typically not used with default)product- Service: ribbon: nfloadbalancerruleclassname: Com.netflix.loadbalancer.RandomRule
3. Springboot Startup class
@SpringBootApplication // Add @enablefeignclients Annotations @EnableFeignClients Public class orderapplication { publicstaticvoid main (string[] args) { Springapplication.run (orderapplication. class , args);} }
4,Productorderserviceimpl Order interface implementation class
Order entity class and Order interface no class is written here, as in the previous article
@Service Public classProductorderserviceimplImplementsProductorderservice {@AutowiredPrivateproductclient productclient; @Override PublicProductorder Save (intUseridintproductId) { //get string data in JSON formatString response =Productclient.findbyid (productId); //JSON string converted to Jsonnode objectJsonnode Jsonnode =Jsonutils.str2jsonnode (response); //encapsulate data into an order entityProductorder Productorder =NewProductorder (); Productorder.setcreatetime (NewDate ()); Productorder.setuserid (USERID); Productorder.settradeno (Uuid.randomuuid (). toString ()); //get product name and commodity priceProductorder.setproductname (Jsonnode.get ("name"). toString ()); Productorder.setprice (Integer.parseint (Jsonnode.get ("Price"). toString ())); //because the cluster is configured in the commodity microservices, it is printed here to see which cluster node is being lowered and the output port number. System.out.println (Jsonnode.get ("name"). toString ()); returnProductorder; }}
5,productclient class
This can be understood as the controller layer of the microservices you need to invoke (this refers to the commodity microservices), which makes the code much more readable than the ribbon.
/***/@FeignClient (name = "Product-service")publicinterface productclient { // Such a combination is equivalent to http://Product-service/api/v1/product/find @GetMapping("/api/v1/product/find") int ID);}
6.Jsonutils Tool Class
/*** JSON Tool class*/ Public classJsonutils {Private Static FinalObjectmapper Objectmappper =NewObjectmapper ();//json String to Jsonnode object method Public Staticjsonnode Str2jsonnode (String str) {Try { returnObjectmappper.readtree (str); } Catch(IOException e) {return NULL; } }}
7, Ordercontroller class
@RestController@RequestMapping("Api/v1/order") Public classOrdercontroller { @Autowired PrivateProductorderservice Productorderservice; @RequestMapping ("Save") PublicObject Save (@RequestParam ("user_id")intUserId, @RequestParam ("product_id")intproductId) { returnProductorderservice.save (UserId, productId); }}
8. View running Results
At the same time it can achieve load balance effect.
second, the concept of explanation
When using feign, pay attention to the use of requestbody, you should use the @postmapping
1. Execution Process
In general, the feign source implementation process is as follows:
(1) First open Feigncleint by @EnableFeignCleints annotations
(2) Implement the interface according to the rules of feign and add @FeignCleint annotations
(3) After the program starts, a packet scan is carried out, scanning all of the @ Feigncleint 's annotated classes, and injecting this information into the IOC container.
(4) When the interface method is called, through the JDK's proxy, to generate the specific requestemplate
(5) Requestemplate in generate request
(6) Request to the client to deal with, wherein the client can be httpurlconnection, httpclient can also be okhttp
(7) The final client is encapsulated into the Loadbalanceclient class, which combines the class Ribbon with load balancing.
2, feign and ribbon comparative advantages
(1) The feign itself contains the ribbon, just for further encapsulation of the ribbon
(2) feign itself is a declarative pseudo-HTTP client, which is more clear and convenient to write.
(3) Fegin is a programming method that uses interface-based annotations for easier
Finally recommended a good source parsing blog: In-depth understanding of feign source parsing.
I just occasionally calm down and ponder over all the past. It's not worth condemning those old times that have been naïve and dull. After all, the days ahead are still long. Keep encouraging yourself,
The day is bright, is a new beginning, but also the unknown Journey (Colonel 7)
Springcloud (5)---feign service call