当前位置:网站首页>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 !
边栏推荐
- 微服务实战|微服务网关Zuul入门与实战
- Connect function and disconnect function of QT
- 汉诺塔问题的求解与分析
- What is the future value of fluorite mine of karaqin Xinbao Mining Co., Ltd. under zhongang mining?
- Sentinel reports failed to fetch metric connection timeout and connection rejection
- 统计字符串中各类字符的个数
- 远程连接IBM MQ报错AMQ4036解决方法
- 一篇详解带你再次重现《统计学习方法》——第二章、感知机模型
- 【Go实战基础】gin 如何绑定与使用 url 参数
- 1、 QT's core class QObject
猜你喜欢

【Go实战基础】gin 如何设置路由

Synchronize files using unison

Matplotlib剑客行——容纳百川的艺术家教程

Dix ans d'expérience dans le développement de programmeurs vous disent quelles compétences de base vous manquez encore?

微服务实战|负载均衡组件及源码分析

【Go实战基础】gin 如何自定义和使用一个中间件

Introduction to the basic concept of queue and typical application examples

一篇详解带你再次重现《统计学习方法》——第二章、感知机模型

数构(C语言--代码有注释)——第二章、线性表(更新版)

C4D quick start tutorial - C4d mapping
随机推荐
统计字符串中各类字符的个数
C# 调用系统声音 嘀~
AMQ6126问题解决思路
「Redis源码系列」关于源码阅读的学习与思考
Pdf document of distributed service architecture: principle + Design + practice, (collect and see again)
Win10 uses docker to pull the redis image and reports an error read only file system: unknown
微服务实战|声明式服务调用OpenFeign实践
【Go实战基础】gin 如何验证请求参数
Shengshihaotong and Guoao (Shenzhen) new energy Co., Ltd. build the charging pile industry chain
Installing Oracle database 19C RAC on Linux
盘点典型错误之TypeError: X() got multiple values for argument ‘Y‘
[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
Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system
Finishing the interview essentials of secsha system!!!
Openshift container platform community okd 4.10.0 deployment
C#钉钉开发:取得所有员工通讯录和发送工作通知
Qt的拖动事件
Avoid breaking changes caused by modifying constructor input parameters
微服务实战|负载均衡组件及源码分析
长篇总结(代码有注释)数构(C语言)——第四章、串(上)