微服务间通讯负载均衡以及日志

2.通信

HTTP Rest http JSON
RPC 远程过程调用 二进制

1.使用 RestTemplate

RestTemplate restTemplate = new RestTemplate();
String forObject = restTemplate.getForObject("http://localhot:8888/user", String.class);

其负载均衡有问题其无法实现健康检查

2.使用Ribbon做负载均衡

做负载均衡靠RestTemplate发请求

默认轮询

1.使用DiscoveryClient

服务发现客户端对象

缺点:

没有负载均衡

@RestController
public class OrderController {

    @Autowired
    private DiscoveryClient discoveryClient;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @GetMapping("/invoke")
    public String invoke(){

        List<ServiceInstance> orders = discoveryClient.getInstances("USERS");
        String result = restTemplate.getForObject(orders.get(0).getUri()+"/user",String.class);
        orders.forEach(System.out::println);
        return result;
    }
}

2.使用LoadBalancerClient

负载均衡客户端对象

缺点:

需要每次先根据服务Id获取负载均衡机器后才能调用服务

@RestController
public class OrderController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/invoke")
    public String invoke(){
        ServiceInstance users = loadBalancerClient.choose("USERS");
        String result = restTemplate.getForObject(users.getUri()+"/user",String.class);
        return result;
    }
}

3.@LoadBalance

用在方法上让方法具有负载均衡的作用

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/invoke")
    public String invoke(){
//        4. 在ResuTemplate上加@LoadBalanced
        String result = restTemplate.getForObject("http://USERS/order", String.class);
        return result;
    }

4.负载均衡

父接口IRule

微服务间通讯负载均衡以及日志_第1张图片

5.OpenFeign

1.写pom

        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>

2.写注解

@EnableFeignClients

3.写接口

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

//调用服务Id
@FeignClient(value = "EMPLOYEES")
public interface EmployeeClient {
    //路径
    @GetMapping("/hello")
    public String hello();

    @GetMapping("/emp")
    public String emp();
}

4.调用

    private static final Logger log = LoggerFactory.getLogger(DepartmentController.class);

    @Autowired
    private EmployeeClient employeeClient;

    @GetMapping("/hello")
    public String hello(){
        String hello = employeeClient.hello();
        String emp = employeeClient.emp();
        log.info("h:{}",hello);
        log.info("e:{}",emp);
        return "dep hello"+","+hello+","+emp;
    }
1.调用时零散参数
1.controller
    @GetMapping("/get/{id}/{name}")
    public String get(@PathVariable("id") Integer id,@PathVariable("name") String name) {
        String result = (String) (id+","+name+","+port);
        System.out.println(result);
        return result;
    }

    @GetMapping("/get1")
    public String get1(@RequestParam("id") Integer id,@RequestParam("name") String name){
        String result =  id+","+name+","+port;
        return result;
    }

    @PostMapping("/obs")
    public Animal getdx(@RequestBody Animal animal){
        return animal;
    }
2.feignclient
    @RequestMapping(value = "/get/{id}/{name}",method = RequestMethod.GET)
    public String get(@PathVariable("id") Integer id,@PathVariable("name") String name);

    @GetMapping("/get1")
    public String get1(@RequestParam("id") Integer id,@RequestParam("name") String name);

    @PostMapping("/obs")
    public Animal getdx(@RequestBody Animal animal);

2.调用多个参数

1.数组
1.调用端
    @GetMapping("/test4")
    public String test4(){
        String[] ids = {"1","2","8848"};
        employeeClient.d1(ids);
        return "ok4";
    }
    
2.feign client
    @GetMapping("/d")
    public String d(@RequestParam String[] ids);

3.被调用端
    @GetMapping("/d")
    public String d(@RequestParam String[] ids){
        System.out.println(ids);
        return "hh";
    }
2.List集合(mvc不接受集合类型所以接的时候变对象来接)
1.调用端
    @GetMapping("/test3")
    public String test3(){
        String[] ids = {"1","2","4564"};
        employeeClient.d(ids);
        return "ok3";
    }
2.feign client
    @GetMapping("/d1")
    public String d1(@RequestParam String[] ids);
3.被调用端

   @GetMapping("/d1")
    public String d1(AnimalIdsVo animalIdsVo){
        System.out.println(animalIdsVo.getIds());
        return "hh1";
    }
4.值对象
package com.wsz.pojo.vo;

import java.util.List;

//vo 值对象
public class AnimalIdsVo {
    public List<String> ids;

    public List<String> getIds() {
        return ids;
    }

    public void setIds(List<String> ids) {
        this.ids = ids;
    }
}

6.响应时处理

使用feignclient时其底层是以json的格式进行传递这时可以使用fastjson处理

1.写pom
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>2.0.11version>
        dependency>
2.使用
    @GetMapping("/test6")
    public String test6(){
        Map<String, Object> data = employeeClient.getMap("1314");
        Object list = data.get("list");
        Object animal = data.get("animal");
        Integer status = (Integer)data.get("status");
        Animal animal1 = JSONObject.parseObject(JSON.toJSONString(animal), Animal.class);
        List<Animal> animals = JSONObject.parseArray(JSON.toJSONString(list), Animal.class);
        log.info("status:{}",status);
        log.info("animal:{}",animal1.toString());
        animals.forEach(animal2 -> log.info("animal2:{}",animal2));
        return "ok";
    }

7.修改openFegin超时时间(默认1s)

#所有服务
feign:
  client:
    config:
      default:
      #连接超时时间为5s
        connectTimeout: 5000
      #等待超时时间为5s
        readTimeout: 5000
        
#单个服务
feign:
  client:
    config:
      EMPLOYEES: #(服务名)
      #连接超时时间为5s
        connectTimeout: 5000
      #等待超时时间为5s
        readTimeout: 5000

8.日志

#开启openfeign日志
logging:
  level:
    com.wsz.feignclient.EmployeeClient: debug
    
feign:
  client:
    config:
      #配置feign日志对象 Map<服务,级别>
      EMPLOYEES:
        loggerLevel: FULL
# 日志级别
## 1.NONE 无
## 2.BASIC 记录请求方法 url 状态码 以及 执行时间
## 3.HEADERS 在2基础上记录请求和响应header
## 4.FULL 记录请求和响应的header body 和元素据 张三全部http协议状态

你可能感兴趣的:(Spring,Cloud,负载均衡,微服务,java)