SpingCloud之feign框架调用
1.生产者(没有什么特殊性)
pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.example</groupId>
- <artifactId>cloud-provider</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>cloud-provider</name>
- <description>Demo project for Spring Boot</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.6.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- <spring-cloud.version>Finchley.SR2</spring-cloud.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.3.2</version>
- </dependency>
- <!--Service Discovery with Zookeeper-->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>${spring-cloud.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <fork>true</fork>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
application.yml
- spring:
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql:///testdb?useSSL=true
- username: root
- password: 123
- cloud:
- zookeeper:
- connect-string: 192.168.3.201:2181
- application:
- name: provider
- mybatis:
- configuration:
- map-underscore-to-camel-case: true
- mapper-locations: classpath:mapper/*Mapper.xml
- logging:
- level:
- com.example.cloudprovider.mapper: debug
实体类
- package com.example.cloudprovider.domain;
- import lombok.Getter;
- import lombok.Setter;
- import java.util.Date;
- @Setter
- @Getter
- public class UserInfo {
- private Integer userId;
- private String userName;
- private int userAge;
- private Date userBirth;
- }
Mapper
- package com.example.cloudprovider.mapper;
- import com.example.cloudprovider.domain.UserInfo;
- public interface UserInfoMapper {
- UserInfo getUser(Integer userId);
- }
Mapper.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.example.cloudprovider.mapper.UserInfoMapper">
- <select id="getUser" resultType="com.example.cloudprovider.domain.UserInfo">
- select user_id, user_name, user_age, user_birth from t_user where user_id = #{userId}
- </select>
- </mapper>
Service接口
- package com.example.cloudprovider.service;
- import com.example.cloudprovider.domain.UserInfo;
- public interface UserService {
- UserInfo getUser(Integer userId);
- }
Service实现
- package com.example.cloudprovider.service.impl;
- import com.example.cloudprovider.domain.UserInfo;
- import com.example.cloudprovider.mapper.UserInfoMapper;
- import com.example.cloudprovider.service.UserService;
- import org.springframework.stereotype.Service;
- import javax.annotation.Resource;
- @Service
- public class UserServiceImpl implements UserService {
- @Resource
- private UserInfoMapper userMapper;
- @Override
- public UserInfo getUser(Integer userId) {
- return userMapper.getUser(userId);
- }
- }
Controller
- package com.example.cloudprovider.controller;
- import com.example.cloudprovider.domain.UserInfo;
- import com.example.cloudprovider.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- public class UserInfoController {
- @Autowired
- private UserService userService;
- @GetMapping("user/{id}")
- public UserInfo getUser(@PathVariable("id") Integer userId) {
- return userService.getUser(userId);
- }
- }
服务发布类
- package com.example.cloudprovider;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- @MapperScan("com.example.cloudprovider.mapper") //扫描Mapper类 注入到Spring容器中
- public class CloudProviderApplication {
- public static void main(String[] args) {
- SpringApplication.run(CloudProviderApplication.class, args);
- }
- }
2.消费者(引入feign框架)
pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.example</groupId>
- <artifactId>cloud-consumer</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>cloud-consumer</name>
- <description>Demo project for Spring Boot</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.6.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- <spring-cloud.version>Finchley.SR2</spring-cloud.version>
- </properties>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>${spring-cloud.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <dependencies>
- <!-- 引入feign依赖 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
- <!--Service Discovery with Zookeeper-->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <fork>true</fork>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
application.yml
- spring:
- cloud:
- zookeeper:
- connect-string: 192.168.3.201:2181
- discovery:
- register: false #不会注册到zk中
- provider: # 服务名称
- ribbon: # 负载均衡实现依靠ribbon
- # 负载策略
- NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机策略 其他策略百度
实体类
- package com.example.cloudconsumer.vo;
- import lombok.Getter;
- import lombok.Setter;
- import java.util.Date;
- @Getter
- @Setter
- public class UserVO {
- private Integer userId;
- private String userName;
- private Date userBirth;
- }
RestTemplate配置类
- package com.example.cloudconsumer.config;
- import org.springframework.boot.SpringBootConfiguration;
- import org.springframework.cloud.client.loadbalancer.LoadBalanced;
- import org.springframework.context.annotation.Bean;
- import org.springframework.web.client.RestTemplate;
- @SpringBootConfiguration
- public class RestTemplateConfiguration {
- @Bean
- @LoadBalanced // Ribbon 负载均衡
- public RestTemplate restTemplate() {
- return new RestTemplate();
- }
- }
Controller
- package com.example.cloudconsumer.controller;
- import com.example.cloudconsumer.vo.UserVO;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.client.RestTemplate;
- @RestController
- public class UserWarpController {
- @Autowired
- private RestTemplate restTemplate;
- // 调用只有一个或者多个服务实例API的情况下
- @GetMapping("warp/user/{userId}")
- public UserVO getUserData(@PathVariable("userId") Integer userId) {
- return restTemplate.getForObject("http://provider/user/"+userId, UserVO.class);
- }
- }
使用框架的Controller
- package com.example.cloudconsumer.controller;
- import com.example.cloudconsumer.client.UserClient;
- import com.example.cloudconsumer.vo.UserVO;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
- import javax.annotation.Resource;
- @RestController
- public class UserFeignController {
- @Resource
- private UserClient userClient;
- // 调用只有一个或者多个服务实例API的情况下
- @GetMapping("feign/user/{userId}")
- public UserVO getUserData(@PathVariable("userId") Integer userId) {
- return userClient.getUserData(userId);
- }
- }
feign调用客户端
- package com.example.cloudconsumer.client;
- import com.example.cloudconsumer.vo.UserVO;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- /**
- * @FeignClient(name = "provider")
- * name为调用服务端的spring.application.name的值
- */
- @FeignClient(name = "provider")
- public interface UserClient {
- @GetMapping("user/{id}")
- public UserVO getUserData(@PathVariable("id") Integer userId);
- }
服务启动类:
- package com.example.cloudconsumer;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- import org.springframework.cloud.openfeign.EnableFeignClients;
- @SpringBootApplication
- @EnableDiscoveryClient //可以发现ZK的服务
- @EnableFeignClients //可以发现feign的服务
- public class CloudConsumerApplication {
- public static void main(String[] args) {
- SpringApplication.run(CloudConsumerApplication.class, args);
- }
- }
总结起来,feign框架可以理解成路由,对url进行再次包装后供给客户端调用,可以在这个路由上进行一系列限制操作,增强安全性。
SpingCloud之feign框架调用的更多相关文章
- Springcloud 整合Hystrix 断路器,支持Feign客户端调用
1,在这篇博文中,已经大致说过了Springcloud服务保护框架 Hystrix在服务隔离,服务降级,以及服务熔断中的使用 https://www.cnblogs.com/pickKnow/p/11 ...
- Spring Cloud Alibaba(8)---Feign服务调用
Feign服务调用 有关Spring Cloud Alibaba之前写过五篇文章,这篇也是在上面项目的基础上进行开发. Spring Cloud Alibaba(1)---入门篇 Spring Clo ...
- thinkphp框架调用类不存在的方法
thinkphp框架调用类不存在的方法调用类不存在的方法,不会报错,但是也不会执行,这是根据tp框架里面的一个魔术方法,框架里面一共才十几个魔术方法
- SpringCloud(5)---Feign服务调用
SpringCloud(5)---Feign服务调用 上一篇写了通过Ribbon进行服务调用,这篇其它都一样,唯一不一样的就是通过Feign进行服务调用. 注册中心和商品微服务不变,和上篇博客一样,具 ...
- Quartz框架调用——运行报错:ThreadPool class not specified
Quartz框架调用——运行报错:ThreadPool class not specified 问题是在于Quartz框架在加载的时候找不到quartz.properties配置文件: 解决方案一: ...
- Quartz框架调用Demo
Quartz框架调用Demo 任务调度在JAVA应用程序中运用的十分普遍,掌握QUARTZ是必备的技能; 官网:http://www.quartz-scheduler.org/ 下载最新1.80资源包 ...
- Spring Cloud Feign 在调用接口类上,配置熔断 fallback后,输出异常
Spring Cloud Feign 在调用接口类上,配置熔断 fallback后,出现请求异常时,会进入熔断处理,但是不会抛出异常信息. 经过以下配置,可以抛出异常: 将原有ErrorEncoder ...
- Spring Boot使用Feign客户端调用远程服务时出现:timed-out and no fallback available,failed and no fallback available的问题解决
timed-out and no fallback available: 这个错误基本是出现在Hystrix熔断器,熔断器的作用是判断该服务能不能通,如果通了就不管了,调用在指定时间内超时时,就会通过 ...
- java使用JNA框架调用dll动态库
这两天了解了一下java调用dll动态库的方法,总的有三种:JNI.JNA.JNative.其中JNA调用DLL是最方便的. ·JNI ·JNA ·JNative java使用 JNI来调用dll动态 ...
随机推荐
- #ifdef 支持Mac #ifndef 支持Windows #if defined (Q_OS_WIN) 应该可以再两个系统通用
//mac qt可以运行 #ifdef Q_OS_MAC qDebug()<<QSysInfo::MacintoshVersion; #endif //Mac不运行 #ifndef Q_O ...
- php-laravel中间件使用
中间件使用 1.项目目录下cmd中php artisan make:middleware adminLogin,创建中间件 2.注册中间件(\Http\kernel.php) protected $r ...
- javaweb(十一)——使用Cookie进行会话管理
一.会话的概念 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学曾 ...
- linux部署MantisBT(一)部署apache
一.部署apache 1.下载apache安装包及依赖包 http://httpd.apache.org/download.cgi#apache24(apache2)http://apr.apache ...
- POJ 3278 Catch That Cow (附有Runtime Error和Wrong Answer的常见原因)
题目链接:http://poj.org/problem?id=3278 Catch That Cow Time Limit: 2000MS Memory Limit: 65536K Total S ...
- KRKR基础篇(二)
这里介绍一些krkr的语法规范,具体的命令含义及用法以后再叙述 一:kag语法及基本概念 KAG使用的剧本语言为KAG Script,文件扩展名为.ks 脚本内的文字除 注释, 命令 , 段落标 ...
- CSP201312-3:最大的矩形
引言:CSP(http://www.cspro.org/lead/application/ccf/login.jsp)是由中国计算机学会(CCF)发起的"计算机职业资格认证"考试, ...
- PytorchZerotoAll学习笔记(四)--线性回归
线性回归 # 导入 torch.torch.autograd的Variable模块import torch from torch.autograd import Variable # 生成需要回归需要 ...
- nginx原声方法按照每天日志切割保存
首先配置日志变量,然后配置日志 在/etc/nginx/conf.d/default.conf 配置变量 server{ if ($time_iso8601 ~ "^(\d{4})-(\d{ ...
- JavaScript之函数柯里化
什么是柯里化(currying)? 维基百科中的解释是:柯里化是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术.意思就是当函 ...