SpringCloud微服务小白也能搭(Hoxton.SR8)(三)Feign|服务消费者

简单上手,直接照搬,就可搭建微服务(Hoxton.SR8) 2020.8.28发布,SpringCloud搭建的文章正在整理,干货不要错过哦

摘要

Spring Cloud OpenFeign 是声明式的服务调用工具,它整合了Ribbon和Hystrix,拥有负载均衡和服务容错功能。Feign是声明式的服务调用工具,我们只需创建一个接口并用注解的方式来配置它,就可以实现对某个服务接口的调用,简化了直接使用RestTemplate来调用服务接口的开发量。Feign具备可插拔的注解支持,同时支持Feign注解、JAX-RS注解及SpringMvc注解。当使用Feign时,Spring Cloud集成了Ribbon和Eureka以提供负载均衡的服务调用及基于Hystrix的服务容错保护功能。

1. 创建一个feign-service模块

注意:配置及搭建参考之前第(一)文章的 客户端 配置

  

1.1pom.xml新增feign依赖

<dependencies>
        <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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
</dependencies>

1.2启动类新增 @EnableFeignClients

package com.zqh.www;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.core.env.Environment;

/**
 * 开启feign
 */
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class FeignServiceApplication {

    private final static Logger logger = LoggerFactory.getLogger(FeignServiceApplication.class);

    public static void main(String[] args) {
        Environment env = SpringApplication.run(FeignServiceApplication.class, args).getEnvironment();
        logger.info(
                "\n----------------------------------------------------------\n\t"
                        + "Application '{}' is running! Access URLs:\n\t"
                        + "Local: \t\thttp://localhost:{}{}"
                        + "\n----------------------------------------------------------",
                env.getProperty("spring.application.name"), env.getProperty("server.port"),
                env.getProperty("server.servlet.context-path") != null ? env.getProperty("server.servlet.context-path") : "");
    }
}

1.3 创建feign消费者service

package com.zqh.www.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;

@FeignClient(value = "user-service", fallback = UserFallbackService.class)
public interface IUserService {

    @GetMapping("/api/user/getUserList")
    Map<String, Object> getUserList();

//    不同传参方式样例
//    JSON格式传参
//    @PostMapping("/user/save")
//    Map<String, Object> save(@RequestBody User user);

//    路径传参
//    @GetMapping("/user/{id}")
//    Map<String, Object> getUser(@PathVariable Long id);

//    表单传参
//    @GetMapping("/user/listUsersByIds")
//    Map<String, Object> listUsersByIds(@RequestParam List<Long> ids);

//    表单传参
//    @GetMapping("/user/getUserByUsername")
//    Result<User> getUserByUsername(@RequestParam String username);
}

1.4 创建熔断处理类

package com.zqh.www.service;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 降级处理类
 */
@Component
public class UserFallbackService implements IUserService {

    @Override
    public Map<String, Object> getUserList() {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", "500");
        resultMap.put("msg", "调用失败,服务被降级");
        resultMap.put("data", null);
        return resultMap;
    }
}

1.5 创建controller测试调用

package com.zqh.www.controller;

import com.zqh.www.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/feign")
public class FeignController {

    @Autowired
    private IUserService userService;

    @GetMapping("/getUserList")
    public Map<String, Object> getUserList() {
        return userService.getUserList();
    }
}

1.6 yml开启feign常用配置以及日志

server:
  port: 8087
spring:
  application:
    name: feign-service
eureka:
  client:
    service-url:
      #注册地址
      defaultZone: http://root:root@localhost:8081/eureka/
  #显示服务器IP加端口
  instance:
    hostname: localhost
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

#feign常用配置
feign:
  hystrix:
    #在Feign中开启Hystrix
    enabled: true
  compression:
    request:
      #是否对请求进行GZIP压缩
      enabled: false
      #指定压缩的请求数据类型
      mime-types: text/xml,application/xml,application/json
      #超过该大小的请求会被压缩
      min-request-size: 2048
    response:
      enabled: false #是否对响应进行GZIP压缩

# 配置feign日志级别
logging:
  level:
    com.jourwon.springcloud.service: debug

2.测试

2.1 正常测试

2.2 负载服务测试

 

2.3 关闭一个服务

结果会出现短暂的服务降级,然后回归正常

 

3.gitee地址

源码参考

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值