通过Swagger获取所有接口方法,缓存至Redis

34 min read
import com.aliyuncs.utils.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import vip.shuashua.repayment.utils.HttpUtils;
import vip.shuashua.repayment.utils.RedisKey;

import java.io.IOException;
import java.util.*;

/**
 * 通过Swagger获取所有接口方法,缓存至Redis
 * Created by LiuJingWei on 2019-09-26.
 */
@Component
public class AdminSwaggerAllMethod implements ApplicationRunner {

    private Logger logger = LoggerFactory.getLogger(AdminSwaggerAllMethod.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    // http://localhost:8081/v2/api-docs
    @Value("${swagger.get.all.method.url}")
    private String SWAGGER_PATH;

    @Override
    public void run(ApplicationArguments args) {
        if (redisTemplate.hasKey(RedisKey.WEB_SWAGGER_ALL_METHOD.getKey())) {
            redisTemplate.delete(RedisKey.WEB_SWAGGER_ALL_METHOD.getKey());
        }
        String swaggerAllMethodJson = getSwaggerAllMethod();
        if (StringUtils.isNotEmpty(swaggerAllMethodJson)) {
            redisTemplate.opsForValue().set(RedisKey.WEB_SWAGGER_ALL_METHOD.getKey(), swaggerAllMethodJson);
            logger.info(String.format("动态通过Swagger解析所有接口方法成功!并加入Redis缓存key:%s,value:%s", RedisKey.WEB_SWAGGER_ALL_METHOD.getKey(), swaggerAllMethodJson));
        } else {
            logger.error("动态通过Swagger解析所有接口方法失败!");
        }
    }

    /**
    * 获取Swagger所有接口方法
    * # 这里注意一点,我们只获取了GET、POST方法
    */
    public String getSwaggerAllMethod(){
        try {
            List<Map<String,Object>> swaggerAllMethod = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            String swaggerJson = HttpUtils.get(SWAGGER_PATH, null, 3000, 3000, "UTF-8");
            Map<String, Object> swaggerMap = objectMapper.readValue(swaggerJson, Map.class);
            LinkedHashMap<String, Object> pathsMap = (LinkedHashMap<String, Object>) swaggerMap.get("paths");// 所有方法
            pathsMap.entrySet().stream().forEach(s -> {
                String method = s.getKey();
                LinkedHashMap<String, Object> methodMode = ((LinkedHashMap<String, Object>) pathsMap.get(s.getKey()));// 所有請求方式GET、POST等
                methodMode.entrySet().stream()
                        .filter(model -> "get".equals(model.getKey()) || "post".equals(model.getKey()))
                        .forEach(m -> {
                            LinkedHashMap<String, Object> methodBody = (LinkedHashMap<String, Object>) methodMode.get(m.getKey());
                            String methodName = (String) methodBody.get("summary");
                            methodBody.entrySet().stream()
                                    .filter(tags -> "tags".equals(tags.getKey()))// tags里是模块名称
                                    .forEach(tags -> {
                                        ArrayList<Object> tagList = (ArrayList<Object>) tags.getValue();
                                        String modeName = (String) tagList.get(0);
                                        Map<String, Object> swaggerMethod = new HashMap<>();
                                        swaggerMethod.put("method", method);
                                        swaggerMethod.put("modelName", modeName);
                                        swaggerMethod.put("methodName", methodName);
                                        swaggerAllMethod.add(swaggerMethod);
                                    });
                        });
            });

            return objectMapper.writeValueAsString(swaggerAllMethod);
        } catch (IOException e) {
            logger.error("通过Swagger解析所有接口异常",e);
            return null;
        }
    }

}