spring-cloud学习之3.使用feign实现负载均衡
一:准备
1.feign依赖
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
3.eureka-cli
<!--eureka 客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
4.配置
server: port: 3001 spring: application: name: dandelion-api eureka: client: service-url: defaultZone: http://localhost:1001/eureka instance: instance-id: ${spring.application.name}:${server.port} prefer-ip-address: true feign: #开启feign熔断支持 hystrix: enabled: true
5.启动类
/** * api * * @author jiang */ @SpringBootApplication @EnableFeignClients public class DandelionApiApplication { public static void main(String[] args) { SpringApplication.run(DandelionApiApplication.class, args); } }
6.案例
/** * 部门信息 * * @author jiang */ @RestController @RequestMapping("/dept") public class SysDeptController { @Autowired private ISysDeptService deptService; @RequestMapping("/list") public R list(SysDept dept) { System.out.println(dept.getPageNum() + ":" + dept.getPageSize()); return deptService.selectDeptList(dept); } }
/** * <p> * 部门表 服务类 * </p>
* * @author jiang * @since 2020-03-18 */ @FeignClient(value = ServiceNameConst.DANDELION_SERVICE, fallback = ISysDeptServiceFallBackImpl.class) public interface ISysDeptService { /** * 查询部门管理数据 * * @param dept 部门信息 * @return 部门信息集合 */ @RequestMapping("/dept/list") R selectDeptList(SysDept dept); }
public static final String DANDELION_SERVICE = "dandelion-service"; 服务名
实现类即是断路回应
/** * 断路 * * @author jiang */ @Component public class ISysDeptServiceFallBackImpl implements ISysDeptService { @Override public R selectDeptList(SysDept dept) { return R.error(); } }