美文网首页
微服务软负载均衡Ribbon

微服务软负载均衡Ribbon

作者: sunpy | 来源:发表于2021-07-18 17:45 被阅读0次

server端

server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

提供者

server:
  port: 8771

#指定注册中心地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

#服务的名称
spring:
  application:
    name: user-service

@RequestMapping("/provider/user")
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @Value("${server.port}")
    private String sourcePort;

    @RequestMapping(value = "/get")
    @ResponseBody
    public User getUserById() {
        User user = userService.getUserById("1");
        user.setName(user.getName() + sourcePort);
        return user;
    }
}

消费者

@SpringBootApplication
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

@RequestMapping("/consumer/user")
@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/get")
    @ResponseBody
    public Result getUser() {
        Result result = new Result();
        result.setCode("0");
        result.setData(restTemplate.getForObject("http://user-service/provider/user/get", Object.class));
        result.setSuccess(true);
        result.setMsg("查询信息成功!");
        return result;
    }
}


Feign

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

@EnableFeignClients
@SpringBootApplication
public class FeignClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignClientApplication.class, args);
    }

}
@FeignClient(name = "user-service")
public interface ProviderService {

    @GetMapping("/provider/user/get")
    String getUserById();
}
@RequestMapping("/feign/client/user")
@RestController
public class UserController {

    @Autowired
    private ProviderService ps;
    
    @RequestMapping("/get")
    @ResponseBody
    public Result getUser() {
        Result result = new Result();
        result.setCode("0");
        result.setData(ps.getUserById());
        result.setSuccess(true);
        result.setMsg("查询信息成功!");
        return result;
    }
}

相关文章

网友评论

      本文标题:微服务软负载均衡Ribbon

      本文链接:https://www.haomeiwen.com/subject/prnwpltx.html