Springcloud Starter Series (2)-feign, ribbon implement rest interface requests and load balancing _springcloud

Source: Internet
Author: User

We introduced the Eureka Service registration component through Springcloud, and implemented the HA with multiple machines, and also registered the Springboot service to Eureka. Today we will mainly introduce how to use these service interfaces as service consumers and implement the soft load balancing based on service. For the previously implemented Springboot rest interface services, generally restful interface to receive and split packets, you can through the Apache httpclient, JDK URLConnection, okhttp and other HTTP request library, Also through the resttemplate provided by spring, we use the Springcloud recommended feign for message parsing to understand its advantages, and why spring strongly recommends a new rest request component, than the traditional use of httpclient, etc. have any advantage. 1. Pom adds feign and ribbon dependent libraries

Create a new Springboot project and add cloud dependencies, this article uses the 1.4.7 version, the specific code can refer to the source after the text, where you need to add to the pom ribbon and feign dependencies. You also need to add dependencies on the Zuul gateway component, and if there is no gateway component, the Hystrix error will be reported at startup, "caused by:java.lang.ClassNotFoundException: Com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect. “

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId> spring-cloud-starter-zuul</artifactid>
        </dependency>
        <dependency>
            <groupid >org.springframework.cloud</groupId>
            <artifactid>spring-cloud-starter-ribbon</artifactid >
        </dependency>
        <dependency>
            <groupid>org.springframework.cloud</groupid >
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
2. Application start class increase feign dependency

In the application class, you need to add a @enablefeignclients annotation in front of the class name, which means that when the application is started, search all classes for interfaces defined as Feignclient and automatically register to spring IOC container, and then automatically dependency injection on all objects that use the client implementation class. There are also eurekaclient annotations because defining the service name of the interface rather than the IP address when feignclient is defined requires eurekaclient to identify the service and implement the soft load.

@SpringCloudApplication
@EnableFeignClients
@EnableEurekaClient Public

class application {

    public static void Main (string[] args) {
        springapplication.run (application.class, args);
    }


3. Create feign Client interface

The most important step below is to define the feign client interface, where the client interface is actually a local definition of the RESTful interface that provides the service, which, when defined, can be used as a remote service interface in other classes like RPC native interface classes. Think about how we use httpclient, okhttp is how to achieve the function of packet reception, first we need to define the HttpClient object, according to the interface requirements of the server to combine the JSON message, and then define a get or post, Different transmission methods also need to invoke different methods (Doget, DoPost), which sends a request out, and then iterates through the stream of bytes from the InputStream or reads the character streams from reader, then deserializes the character streams into objects, all of which require coding implementations, The entire process, although structurally clear but cumbersome, is why RPC was so hot, because using RPC makes it easier for the client to invoke the remote service interface, as simple as using a local object, But the biggest drawback with RPC is that every client needs to maintain a client jar package for the server, which in fact defines the interface, and once the server interface changes, the service consumer needs to update the jar package, which makes the client strong on the server. Feign is a good solution to this problem, in the client and server side is not dependent on the situation, let the client use the service as simple as using the local interface, nonsense, the following to define feign client interface, The interface of the service side here uses the previously defined GetUser interface.

@FeignClient ("Usercenter-provider") public

interface Userfeignclient {
    //feign defines the service provider interface
    @ Requestmapping (value = "/getuser", method = Requestmethod.post, produces = {"Application/json;charset=utf-8"})
    String GetUser (@RequestBody string data);


The @FeignClient ("usercenter-provider") annotation means that the method defined in the interface is all "Usercenter-provider", a method provided by the Serviceid, Note that the Serviceid needs to be consistent with the name of the service provider defined in Eureka server, otherwise feign cannot find the service, feign internally integrates ribbon so after the service is found through Serviceid, Through Ribbon automatic service access load balancing, you can define Ribbon load balancing method to achieve what you want, by default, the random access method can also be defined as order, access weights, or custom load algorithms, where the default load is used, The default load has been able to meet most of the requirements. Before the method of an interface needs to define information such as access path and access method and encoding format of the method, the request parameter can also be set by @requestbody or @requestparameter value method, where the parameter set with the same name as the argument name is used. Is it easy to define a remote server-side interface? 4. Remote Service Interface uses

The feign client interface is defined above, and it is easy to use later, where the service layer and controller are defined according to the daily project structure, and the feign interface call is placed in the service implementation class. In the Controller class for service calls, here need to pay attention to a problem, before the test in the process of their own encounter, because accidentally write wrong, made a very low-level error, found 1 hours to find the reason. Because feign's client is automatically injected by the time the @autowired is started, this allows the service to be hosted in the spring IOC if the client call is in service. Or you'll report your service. There is no definition, and when controller uses this service, it should be automatically injected into the service implementation through the IOC container, or it will report a client null pointer error, If you find the feignclient call in the debugging process Nullpoint, basically because of the IOC bean hosting problems, I was writing a wrong line of code caused the problem.
Userserviceimpl.java

@Service public
class Userserviceimpl implements UserService {
    @Autowired
    private userfeignclient userfeignclient;
    @Override public
    string GetUser (String data) {return
        "feign:" + userfeignclient.getuser (data);
    }
}

Usercontroller.java

@RestController public
class Usercontroller {
    @Autowired
    private userservice userservice;

    @RequestMapping (value = "/getuser", method = Requestmethod.post, produces = {"Application/json;charset=utf-8"})
    public string GetUser (@RequestBody string data) {return
        userservice.getuser (data);
    }
}
5. APPLICATION.YML parameter setting

The main configuration is to configure the address of the Eureka server cluster, because you need to define which Eureka cluster to find the Serviceid that feign uses.

Spring:
  application:
    name:springcloud-feign-ribbon

server:
  port:8080

Eureka:
  Client:
    serviceurl:
      defaultzone:http://node1:8761/eureka/,http://node2:8762/eureka/

Summary

Finally, we start the Eureka Server, Usercenter-provider Services, and then start the application of this write.
Image
The following httprequester to initiate the request, the address bar input http://node1:8080/getUser,body column input {"name": "Feiweiwei"}, you can see the return of feign {"Name": " Feiweiwei "}
Image

Source git address: https://github.com/feiweiwei/springcloud-feign

Author: monkey01
Link: https://www.jianshu.com/p/ 270F3CD658F1
Source: Jane book
Copyright is owned by the author. Commercial reprint please contact the author to obtain authorization, non-commercial reprint please indicate the source.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.