当前位置:网站首页>Microservice practice | declarative service invocation openfeign practice
Microservice practice | declarative service invocation openfeign practice
2022-07-02 09:10:00 【_ Time boiled the rain】
Last one Micro service practice | Load balancing components and source code analysis
List of articles
OpenFeign Introduce
In limine , We use native DiscoveryClient Discover services and use RestTemplate Make calls between services , Then we manually developed a load balancing component , Finally, the load balancing component is introduced Ribbon. Each chapter invokes services in different ways , The common ground is that they are all based on RestTemplate To achieve , Presumably, everyone will find this calling method a little troublesome , Write the request protocol before each call , The service name , The name of the interface 、 Assembly parameters 、 Processing response data types , These are all repetitive tasks , The code is also highly similar , Only URL Different , The request method is different 、 Different parameters , Everything else is basically the same , In that case , Is there any way to simplify the request ? In this article, we will talk about declarative microservice invocation OpenFeign .
OpenFeign Is a display declarative WebService client . Use OpenFeign Can make writing Web Service The client is simpler . When using, you only need to define the service interface , Then add comments on it .OpenFeign It also supports pluggable encoders and decoders .spring cloud Yes feign It was packaged , To support MVC Notes and HttpMessageConverts. and eureka( Service registry ) and ribbon Combination can realize load balancing . stay Spring Cloud Use in OpenFeign, It can be used HTTP Request access to remote services , It's like calling a local method , Developers are totally unaware that this is a call to a remote method , More imperceptible in the visit HTTP request , Very convenient
- OpenFeign Design purpose based simplification Java Http Client development .Feign stay restTemplate Further encapsulation is made on the basis of , It helps us define and implement the definition of dependent service interfaces . stay OpenFeign With the help of , We just need to create an interface and configure it with annotations ( Be similar to Dao On the interface Mapper annotation ) You can complete the interface binding to the service provider , Greatly simplified Spring cloud Ribbon Development of , Development volume of auto encapsulation service calling client .
- OpenFeign Integrated Ribbon, utilize ribbon Maintained service list , And through ribbon The load balancing of the client is realized . And ribbon The difference is , adopt OpenFeign Just define the service binding interface and use the declarative method , Elegant and simple implementation of service invocation .
Project practice
Create project
Next , Start our project practice , Create two services , One is dms( It is the code meter service , Provide various drop-down options ), One is application system app( The actual business system )
First create the name dms Of maven project , Introduce dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
</dependencies>
create profile :
server:
port: 8003
spring:
application:
name: dms
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
logging:
pattern:
console: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n'
Write the startup class
/** * @Author: official account : The programmer 965 * @create 2022-06-20 **/
@EnableDiscoveryClient
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class DmsApplication {
public static void main(String[] args) {
SpringApplication.run(DmsApplication.class, args);
}
}
Note that this time , We added @EnableFeignClients and @EnableDiscoveryClient annotation .
To write api Module code , Note that this is an interface to provide external services , The service name of the interface is dms, according to code Code value get name :
/** * @Author: official account : The programmer 965 * @create 2022-06-20 **/
@FeignClient(value = "dms")
public interface DmsApi {
@RequestMapping(value="/dict/{code}", method = RequestMethod.GET)
public String findNameByCode(@PathVariable("code") String code);
}
To write controller class , Can achieve DmsApi Interface , Here is a simple example of gender :
/** * @Author: official account : The programmer 965 * @create 2022-06-20 **/
@RestController
public class DmsController implements DmsApi {
@Override
public String findNameByCode(String code) {
switch (code){
case "0" :
return " male ";
case "1" :
return " Woman ";
default:
return " Unknown ";
}
}
}
dms The module is developed .
alike , establish app modular , Note the need to introduce dms modular , In order to call its interface
<dependencies>
<dependency>
<groupId>com.cxy965</groupId>
<artifactId>dms</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
establish controller layer : Inject here dmsApi, And pass dmsApi Call its findNameByCode() Method , You can complete the calling code of the service !
/** * @Author: official account : The programmer 965 * @create 2022-06-20 **/
@RestController
public class AppController {
@Autowired
private DmsApi dmsApi;
@RequestMapping("/index")
public String index(){
String nameByCode = dmsApi.findNameByCode("1");
return nameByCode;
}
}
Start class
/** * @Author: official account : The programmer 965 * @create 2022-06-20 **/
@EnableEurekaClient
@SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}
Start project validation
Returned the correct result , When there are multiple registration centers dms The service , When called, it will automatically play the role of load balancing .
summary
OpenFeign yes Spring Cloud A member of the family , Its core function is to HTTP Formal Rest API It provides a very simple and efficient RPC Call mode . if Spring Cloud Other members address system level availability , Scalability issues , that OpenFeign It solves the development efficiency problem that is most closely related to the interests of developers . In this article, we learned Feign Integration and basic use of components , The next article will write Feign More use of , Let's hope together !
边栏推荐
- 统计字符串中各类字符的个数
- "Redis source code series" learning and thinking about source code reading
- Ora-12514 problem solving method
- Sentinel reports failed to fetch metric connection timeout and connection rejection
- [go practical basis] how to install and use gin
- [go practical basis] how can gin get the request parameters of get and post
- Mirror protocol of synthetic asset track
- C# 调用系统声音 嘀~
- 微服务实战|手把手教你开发负载均衡组件
- C4D quick start tutorial - C4d mapping
猜你喜欢
Ora-12514 problem solving method
History of Web Technology
Matplotlib剑客行——布局指南与多图实现(更新)
Minecraft plug-in service opening
Sentinel reports failed to fetch metric connection timeout and connection rejection
概念到方法,绝了《统计学习方法》——第三章、k近邻法
Minecraft air Island service
Function ‘ngram‘ is not defined
How to realize asynchronous programming in a synchronous way?
【Go实战基础】gin 如何获取 GET 和 POST 的请求参数
随机推荐
WSL installation, beautification, network agent and remote development
汉诺塔问题的求解与分析
Solution and analysis of Hanoi Tower problem
Redis sorted set data type API and application scenario analysis
Shengshihaotong and Guoao (Shenzhen) new energy Co., Ltd. build the charging pile industry chain
Matplotlib剑客行——布局指南与多图实现(更新)
The channel cannot be viewed when the queue manager is running
gocv opencv exit status 3221225785
Gocv image cutting and display
NPOI 导出Word 字号对应
微服务实战|负载均衡组件及源码分析
C Gaode map obtains the address according to longitude and latitude
Cloud computing in my eyes - PAAS (platform as a service)
【Go实战基础】gin 如何获取 GET 和 POST 的请求参数
[staff] common symbols of staff (Hualian clef | treble clef | bass clef | rest | bar line)
[staff] the lines and spaces of the staff (the nth line and the nth space in the staff | the plus N line and the plus N space on the staff | the plus N line and the plus N space below the staff | the
1、 QT's core class QObject
Leetcode sword finger offer brush questions - day 22
libusb的使用
gocv opencv exit status 3221225785