ny
昨天 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package jnpf.handler;
 
import cn.dev33.satoken.context.model.SaRequest;
import jnpf.util.ReactorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.util.Assert;
 
import java.util.List;
 
/**
 * 同一个用户上传文件, 路由至同一台机器, 避免分片上传文件合并失败
 *
 * @author JNPF开发平台组
 * @version V3.5.0
 * @copyright 引迈信息技术有限公司(https://www.jnpfsoft.com)
 * @date 2024-01-10
 */
@Slf4j
public class FileChunkLoadBalancerHandler implements ILoadBalancerHandler{
    @Override
    public boolean isSupport(String serviceId, String uri) {
        return uri.endsWith("/chunk") || uri.endsWith("/merge");
    }
 
    @Override
    public Response<ServiceInstance> choose(String serviceId, List<ServiceInstance> serviceInstances, SaRequest request) {
        //根据用户TOKEN路由
//        String routerKey = SaHolder.getRequest().getHeader(Constants.AUTHORIZATION);
//        if(StringUtil.isEmpty(routerKey)) {
//            routerKey = ReactorUtil.getIpAddr();
//        }
        //根据来访IP轮询
        String routerKey = ReactorUtil.getIpAddr(request);
        int hash = Math.max(routerKey.hashCode() % serviceInstances.size(), 0);
        ServiceInstance serviceInstance = serviceInstances.get(hash);
        if(serviceInstance == null){
            log.error("获取分片服务为空:{}, {}, {}", serviceId, hash, serviceInstances);
            return new EmptyResponse();
        }
        log.debug("file chunk route to: {}", serviceInstance.getInstanceId());
        return new DefaultResponse(serviceInstance);
    }
}