Sample
以 finance 模块 调用 exchange 模块 的 MarketService 为例。
Steps
服务提供者(exchange):搭建接口
- 在 exchange-api 下,新建 MarketDto 和 MarketServiceFeign。并在 exchange-service 下使用 MapStruct 进行映射。
在 dto 包,
java
@Data
@ApiModel(value = "Market RPC数据的传输对象")
public class MarketDto {
// ......(一些属性)
}
在 feign 包,
java
@FeignClient(name = "exchange-service", configuration = OAuth2FeignConfig.class, path = "/markets")
public interface MarketServiceFeign {
@GetMapping("/getMarket")
MarketDto findByCoinId(Long sellCoinId, Long buyCoinId);
}
在 mappers 包,
java
// MapStruct 会自动生成实现类
@Mapper(componentModel = "spring")
public interface MarketDtoMappers {
MarketDtoMappers INSTANCE = Mappers.getMapper(MarketDtoMappers.class);
MarketDto entity2Dto(Market market);
Market dto2Entity(MarketDto marketDto);
List<MarketDto> entity2Dto(List<Market> market);
List<Market> dto2Entity(List<MarketDto> marketDto);
}
- 在 exchange-service 的 MarketController 下实现 MarketServiceFeign,
java
@RestController
@RequestMapping("/markets")
@Api(tags = "交易市场的控制器")
public class MarketController implements MarketServiceFeign {
// ......(其他controller)
@Override
public MarketDto findByCoinId(Long sellCoinId, Long buyCoinId) {
MarketDto marketDto = marketService.findByCoinId(buyCoinId, sellCoinId);
return marketDto;
}
服务消费者(finance):调用接口
在 finance-service 的对应实现类注入 MarketServiceFeign 并调用方法,
java
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService{
@Autowired
private MarketServiceFeign marketServiceFeign;
@Override
public UserTotalAccountVo getUserTotalAccount(Long userId) {
// ......(业务逻辑)
// 调用 Feign 远程接口
MarketDto marketDto = marketServiceFeign.findByCoinId(basicCoinId, coinId);
// ......
}