spring-cloud学习之4.微服务请求打通
一:前提
我们上一篇中已经配置好了feign,本次我们配置服务端service,来实现getway->api->service的请求流程。
1.pom
<!--eureka 客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
2.配置
本次只需要配置eureka客户端即可
server: port: 4001 spring: application: name: dandelion-service datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver druid: url: jdbc:mysql://localhost:3306/dandelion?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: 123456 mybatis-plus: mapper-locations: classpath*:/mapper/**/*Mapper.xml type-aliases-package: club.dandelion.cloud.service.entity eureka: client: service-url: defaultZone: http://localhost:1001/eureka instance: instance-id: ${spring.application.name}:${server.port} prefer-ip-address: true #访问路径可以显示IP地址
3.contr
import club.dandelion.cloud.common.R; import club.dandelion.cloud.service.base.BaseController; import club.dandelion.cloud.service.entity.SysDept; import club.dandelion.cloud.service.service.ISysDeptService; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 部门 提供者 * * @author zmr * @date 2019-05-20 */ @RestController @RequestMapping("dept") @Slf4j public class SysDeptController extends BaseController { @Autowired private ISysDeptService sysDeptService; @Value("${server.port}") private String port; /** * 查询部门列表 */ @RequestMapping("list") public R list(SysDept sysDept) { log.info("端口:" + port); Page<SysDept> page = new Page<>(sysDept.getPageNum(), sysDept.getPageSize()); List<SysDept> list = sysDeptService.selectDeptList(page, sysDept); page.setRecords(list); return R.ok(port); } }
4.启动多个实例
idea可以启动多个实例,具体操作百度。
我们把之前的项目启动
1001:注册中心
2001:getwang网关
3001:feign
4001/4002:服务实现类,完全一样的项目,只是端口不同
5.示例
feign默认轮询,可单独配置某个服务比重。
6.配置负载均衡策略
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
#服务名
dandelion-service:
ribbon:
# 负载方式
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
具体的策略方式有很多,请查看官方文档或百度