<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
@EnableFeignClients
@MapperScan("cn.zyw.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
import cn.zyw.order.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient("userservice")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private UserClient userClient;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2.用Feign远程调用
User user = userClient.findById(order.getUserId());
// 3. 封装user到Order
order.setUser(user);
// 4.返回
return order;
}
}
feign:
client:
config:
default: # 这里用default就是全局配置,
logger-level: : basic
feign:
client:
config:
userservice: # userservice为服务名
logger-level: : basic
声明一个Bean
import feign.Logger;
import org.springframework.context.annotation.Bean;
public class FeignClientConfiguration {
@Bean
public Logger.Level feignLogLevel(){
return Logger.Level.BASIC;
}
}
@EnableFeignClients(defaultConfiguration = FeignClientConfiguration.class)
@FeignClient(value = "userservice", configuration = FeignClientConfiguration.class)
<dependency>
<groupId>io.github.openfeigngroupId>
<artifactId>feign-httpclientartifactId>
dependency>
feign:
httpclient:
enabled: true # 开启feign对httpclient的支持
max-connections: 200 # 最大连接数
max-connections-per-route: 50 # 每个路径的最大连接数
feign-api子模块其他模块引入feign-api依赖,@EnableFeignClients属性中增加basePackages或clients属性
<dependency>
<groupId>cn.zyw.demogroupId>
<artifactId>feign-apiartifactId>
<version>1.0version>
dependency>
@EnableFeignClients(basePackages = "cn.zyw.feign.clients", defaultConfiguration = FeignClientConfiguration.class)
@EnableFeignClients(clients = {UserClient.class}, defaultConfiguration = FeignClientConfiguration.class)