Feign:微服务之间互相调用
Consul:服务注册中心
<!-- consul 服务注册和发现功能 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!-- 使用feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
关于Consul的yml语法
spring:
cloud:
consul:
host: 127.0.0.1
port: 8500
discovery:
register: true # 配置服务注册到Consul上
deregister: true
healthCheckPath: ${server.servlet.context-path}/health # 配置服务健康检查地址,供Consul调用。检查默认为“/ health”
healthCheckInterval: 10s
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # 注册ID
enabled: true # 不禁用Consul Discovery Client
prefer-ip-address: false # true表示注册时IP而不是hostname
hostname: 127.0.0.1
service-name: ${spring.application.name}
对于consul 的心跳检查我写在了spring Boot 的启动文件中
@RestController
@SpringBootApplication
@MapperScan("mas.order.mapper") //扫描mapper
@EnableFeignClients(basePackages = {"mas.order.service"})//扫描Feign
public class OrderApplication {
static {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
}
@Value("${spring.cloud.client.ip-address}")
String localIpAddress;
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@GetMapping("/health")
public String check() {
return "SUCCESS;ip:" + localIpAddress;
}
}
关于Feign的yml语法
feign:
client:
config:
default:
connectTimeout: 60000
readTimeout: 60000
loggerLevel: BASIC
directUrl: # 直连配置 :为空时 使用注册中心的服务;不为空,使用配置的链接,
storage: http://localhost:8524
pay: http://localhost:8522
在调用者的微服务中创建一个service接口 PayService
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = "pay",
name = "pay",
url = "${feign.client.directUrl.pay}",
primary = false)
public interface PayService {
/**
* 使用Feign时,请求路径和客户端调用一致,在yml写好了ip和端口,在这里写服务名和详细的请求路径
* @return "success"
*/
@GetMapping("/pay/account/success")
String success();
}
记得在使用这个Feign类的时候要在启动类上面加注解@EnableFeignClients来扫描该路径
下面是测试过程
//被调用者
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService service;
@GetMapping("/success")
public String success() {
return "success";
}
}
//调用者 在业务类中调用创建在自己服务里的PayService
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements IOrderService {
@Autowired
private PayService payService;
@Override
public String successFeign() {
return payService.success();
}
}
结果