当前位置:网站首页>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 !
边栏推荐
- 西瓜书--第五章.神经网络
- Solution of Xiaomi TV's inability to access computer shared files
- MYSQL安装出现问题(The service already exists)
- cmd窗口中中文呈现乱码解决方法
- win10使用docker拉取redis镜像报错read-only file system: unknown
- Count the number of various characters in the string
- C4D quick start tutorial - Chamfer
- Redis zadd导致的一次线上问题排查和处理
- Linux binary installation Oracle database 19C
- Openshift container platform community okd 4.10.0 deployment
猜你喜欢

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

Servlet全解:继承关系、生命周期、容器和请求转发与重定向等

commands out of sync. did you run multiple statements at once

C language - Blue Bridge Cup - 7 segment code

QT -- how to set shadow effect in QWidget

C nail development: obtain all employee address books and send work notices

远程连接IBM MQ报错AMQ4036解决方法

【Go实战基础】如何安装和使用 gin

「Redis源码系列」关于源码阅读的学习与思考

Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`
随机推荐
Complete solution of servlet: inheritance relationship, life cycle, container, request forwarding and redirection, etc
Redis sorted set data type API and application scenario analysis
Cloudreve自建云盘实践,我说了没人能限制得了我的容量和速度
NPOI 导出Word 字号对应
C language - Blue Bridge Cup - 7 segment code
[go practical basis] how to customize and use a middleware in gin
gocv opencv exit status 3221225785
Cloudrev self built cloud disk practice, I said that no one can limit my capacity and speed
Jd.com interviewer asked: what is the difference between using on or where in the left join association table and conditions
Sentinel reports failed to fetch metric connection timeout and connection rejection
西瓜书--第五章.神经网络
Qt的拖动事件
C Baidu map, Gaode map, Google map (GPS) longitude and latitude conversion
Redis zadd导致的一次线上问题排查和处理
Flink - use the streaming batch API to count the number of words
微服务实战|熔断器Hystrix初体验
微服务实战|负载均衡组件及源码分析
MYSQL安装出现问题(The service already exists)
Qt的右键菜单
Solution and analysis of Hanoi Tower problem