可以看到若依设计很巧妙,为了任何模块进行用户、文件、日志服务调用,单独抽离成为一个模块。
tips:像部门可以加入缓存当中,没有必要进行服务调用。
模仿上图,调用系统模块中的部门Controller中的接口
package com.rjgf.system.api;
import com.rjgf.common.core.constant.SecurityConstants;
import com.rjgf.common.core.constant.ServiceNameConstants;
import com.rjgf.common.core.domain.R;
import com.rjgf.system.api.domain.SysDept;
import com.rjgf.system.api.factory.RemoteDeptFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import java.util.Map;
/**
* 部门服务
*
* @author
*/
@FeignClient(contextId = "remoteDeptService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteDeptFallbackFactory.class)
public interface RemoteDeptService {
/**
* 获取部门列表
*
* @param source 请求来源
* @return 结果
* @RequestParam GET请求要指定类型 默认为POST请求
*/
@GetMapping("/dept/remote/map")
R<Map<Long, SysDept>> map(@RequestHeader(SecurityConstants.FROM_SOURCE) String source);
}
当服务调用失败,降级进入方法
package com.rjgf.system.api.factory;
import com.rjgf.common.core.domain.R;
import com.rjgf.system.api.RemoteDeptService;
import com.rjgf.system.api.domain.SysDept;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 部门服务降级处理
*
* @author rjgf
*/
@Component
public class RemoteDeptFallbackFactory implements FallbackFactory<RemoteDeptService> {
private static final Logger log = LoggerFactory.getLogger(RemoteDeptFallbackFactory.class);
@Override
public RemoteDeptService create(Throwable throwable) {
log.error("部门服务调用失败:{}", throwable.getMessage());
return new RemoteDeptService() {
@Override
public R<Map<Long, SysDept>> map(String source) {
return R.fail("部门服务调用失败:" + throwable.getMessage());
}
};
}
}
部门Controller中的接口
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {
/**
* 获取部门map
*/
@InnerAuth
@GetMapping("/remote/map")
public R<Map<Long, SysDept>> map() {
Map<Long, SysDept> collect = deptService.selectDeptList(new SysDept())
.stream().collect(Collectors.toMap(SysDept::getDeptId, o -> o));
return R.ok(collect);
}
}
正常SpringBoot项目就能生效了,若依核心模块不会自动注入,需要指定下。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.rjgf.system.api.factory.RemoteUserFallbackFactory,\
com.rjgf.system.api.factory.RemoteLogFallbackFactory, \
com.rjgf.system.api.factory.RemoteFileFallbackFactory,\
com.rjgf.system.api.factory.RemoteDeptFallbackFactory
如果是调用的是自定义模块,在SpringApplication上标识注解
@EnableRyFeignClients
在需要使用的地方注入使用
@Autowired
private RemoteDeptService remoteDeptService;
R<Map<Long, SysDept>> remoteDeptRusult = remoteDeptService.map(INNER);
if (R.FAIL == remoteDeptRusult.getCode()) {
throw new BaseException("请联系系统管理员");
}