程序员Java 杂谈Java学习笔记

Sprig Cloud(五):Feign

2018-04-04  本文已影响392人  聪明的奇瑞

简介

快速入门

restTemplate.getForObject("http://flim-user/"+id,User.class);
Map<String,Object> map = new HashMap<>();
map.put("name","张三");
map.put("username","account1");
map.put("age",20);
this.restTemplate.getForObject(" http://localhost:8010/search?name={name}&username={username}&age={age}",User[].class,map);

服务消费者整合 Feign

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.4.RELEASE</version>
</dependency>
@FeignClient(name = "film-user")       // 服务提供者名称
public interface UserFeignClient {
    @GetMapping("/{id}")
    UserEntity findById(@PathVariable("id") int id);
}
@FeignClient(name = "film-user",url = "http://localhost:8080")
@Autowired
private UserFeignClient userFeignClient;

@GetMapping("/user/{id}")
public UserEntity findById(@PathVariable int id){
    return userFeignClient.findById(id);
}

自定义 Feign 配置

@Configuration
public class FeignConfiguration {
    //使用Feign自带的注解
    @Bean
    public Contract feignContract(){
        return new feign.Contract.Default();
    }
}
@FeignClient(name = "film-user",configuration = FeignConfiguration.class)
public interface UserFeignClient {
    //使用Feign自带的注解@RequestLine
    @RequestLine("GET /{id}")
    UserEntity findById(@PathVariable("id") int id);
}

手动创建 Feign

修改服务提供者

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("password1").roles("USER")
                .and()
                .withUser("admin").password("password2").roles("ADMIN")
                .and()
                .passwordEncoder(this.passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //所有请求都要经过httpBasic认证
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //返回一个明文密码器,Spring 提供给我们做明文测试的
        return NoOpPasswordEncoder.getInstance();
    }
}
@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    private final Logger log = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/{id}")
    public User findById(@PathVariable int id){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        org.springframework.security.core.userdetails.User principal = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        log.info("当前的用户是{},角色是{}",principal.getUsername(),authorities.stream()
                .map((GrantedAuthority e) -> e.getAuthority()).collect(Collectors.joining(",")));
        User user = userRepository.findOne(id);
        return user;
    }
}
 com.linyuan.controller.UserController    : 当前的用户是user,角色是ROLE_USER
 com.linyuan.controller.UserController    : 当前的用户是admin,角色是ROLE_ADMIN

修改服务消费者

@Import(FeignClientsConfiguration.class)
@RestController
public class MovieController {
private UserFeignClient adminFeignClient;

    private UserFeignClient userFeignClient;

    @Autowired
    public MovieController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
        this.userFeignClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract)
                .requestInterceptor(new BasicAuthRequestInterceptor("user","password1"))
                .target(UserFeignClient.class,"http://film-user/");
        this.adminFeignClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract)
                .requestInterceptor(new BasicAuthRequestInterceptor("admin","password2"))
                .target(UserFeignClient.class,"http://film-user/");
    }

    @GetMapping("/user/{id}")
    public UserEntity findByIdUser(@PathVariable int id){
        return userFeignClient.findById(id);
    }

    @GetMapping("/admin/{id}")
    public UserEntity findByIdAdmin(@PathVariable int id){
        return adminFeignClient.findById(id);
    }
}

Feign 对压缩的支持

feign.compression.request.enabled = true
feign.compression.response.enabled = true
feign.compression.request.enabled = true
feign.compression.request.mine-types = text/xml,application/xml,application/json    #默认配置
feign.compression.request.min-request-size = 2048   #默认配置

Feign 日志

@Configuration
public class FeignConfiguration {
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.BASIC;
    }
}
@FeignClient(name = "film-user",configuration = FeignConfiguration.class)
public interface UserFeignClient {
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    UserEntity findById(@PathVariable("id") int id);
}
logging:
  level: 
    com.linyuan.request.UserFeignClient: DEBUG  #Feign的Logger.Level只对DEBUG作出响应/
2017-12-22 11:41:34.387 DEBUG 7405 --- [nio-8010-exec-3] com.linyuan.request.UserFeignClient      : [UserFeignClient#findById] ---> GET http://flim-user/1 HTTP/1.1
2017-12-22 11:41:34.395 DEBUG 7405 --- [nio-8010-exec-3] com.linyuan.request.UserFeignClient      : [UserFeignClient#findById] <--- HTTP/1.1 200 (8ms)
2017-12-22 11:41:35.001 DEBUG 7405 --- [nio-8010-exec-5] com.linyuan.request.UserFeignClient      : [UserFeignClient#findById] ---> GET http://flim-user/1 HTTP/1.1
2017-12-22 11:41:35.012 DEBUG 7405 --- [nio-8010-exec-5] com.linyuan.request.UserFeignClient      : [UserFeignClient#findById] <--- HTTP/1.1 200 (10ms)
2017-12-22 11:41:35.591 DEBUG 7405 --- [nio-8010-exec-4] com.linyuan.request.UserFeignClient      : [UserFeignClient#findById] ---> GET http://flim-user/1 HTTP/1.1
2017-12-22 11:41:35.602 DEBUG 7405 --- [nio-8010-exec-4] com.linyuan.request.UserFeignClient      : [UserFeignClient#findById] <--- HTTP/1.1 200 (11ms)

Feign 构造多参数请求

GET 请求多参数

POST 请求多参数

@RestController
public class UserController{
    @PostMapping("/post")
    public User post (@RequestBody User user){
        ...
    }
}
@FeignClient(name = "flim-user")
public interface UserFeignClient {
    @RequestMapping(value = "/post", method = RequestMethod.POST)
    UserEntity post(@RequestBody User user);
}
上一篇下一篇

猜你喜欢

热点阅读