小技巧合集

Spring MVC

返回数据时json处理忽略null字段

1
2
3
4
spring:
jackson:
default-property-inclusion: non_null
# 返回数据时json处理忽略null字段

Feign

解决服务A请求服务B需要登录验证等

这里配置了一个代理类, 在Feign请求时会执行它, 这时加上Cookies, 就实现了Feign携带Cookie请求, 有点类似AOP

  • FeignClient类

    添加@FeignClient(name = "user-service", configuration = FeignConfig.class)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    package com.leyou.user.client;


    import com.leyou.auth.config.FeignConfig;
    import com.leyou.user.dto.AddressDTO;
    import com.leyou.user.dto.UserDTO;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.*;

    @FeignClient(name = "user-service", configuration = FeignConfig.class)
    public interface UserClient {

    /**
    * 根据手机号和密码查询用户
    * @param username 手机号
    * @param password 密码
    * @return 用户信息
    */
    @GetMapping("/info")
    UserDTO queryUserByPhoneAndPassword(
    @RequestParam("username") String username, @RequestParam("password") String password);



    /**
    * 根据收货地址id查询用户收货地址
    * @return 收货地址列表
    */
    @PostMapping("/info/address")
    AddressDTO queryAddressById(@RequestParam Long id);
    }
  • FeignConfig类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.leyou.auth.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;


// 配置Feign, 设置token, 因为user中的有些地址需要检测用户是否登录
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = null;

if (attributes != null) {
request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
if("cookie".equals(name)) {
Enumeration<String> values = request.getHeaders(name);
while (values.hasMoreElements()) {
String value = values.nextElement();
requestTemplate.header(name, value);
}
}
}
}

}
}