Springcloud微服务之间调用

Springcloud之间的调用
1、符合该架构规范的@FeignClient访问方式,feign在Springcloud中的使用。

(1)添加feign依赖

[Java] 纯文本查看 复制代码
?

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
(2)创建feignClient

[Java] 纯文本查看 复制代码
?

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

//@FeignClient(value = "offerprpall")
@FeignClient(name = "offerprpall",url = "http://10.75.5.10:19225/")
@Service
public interface LoginIntializtionFeign {

/**
 *  @description: 初始界面开关加载
 *  @param:InitializationQueryVo  入参
 *  @return InitializationResponseVo 返参
 */
@RequestMapping(value = "/comCode/comCodeApi",method = {RequestMethod.POST})
public InitializationResponseVo loginIntializtion(@RequestBody InitializationQueryVo queryVo) throws Exception;//复合类型好像默认是POST请求

@RequestMapping( value = "/findAll/{name}",method = RequestMethod.GET)
public List<SpringUser> findAll(@PathVariable("name") String name);//get方式
@FeignClient(value = "offerprpall")这种方式是常见的写法, 用于通知Feign组件对该接口进行代理(不需要编写接口实现),name属性指定我们要调用哪个服务,不带URl的是在注册中心已经配置好。使用者可直接通过@Autowired注入。如下

[AppleScript] 纯文本查看 复制代码
?
1
2
<font style="color:rgb(79, 79, 79)"><font face="-apple-system, &quot;"><font style="font-size:16px">@Autowired
private LoginIntializtionFeign loginIntializtionFeign;</font></font></font>
@RequestMapping表示在调用该方法时需要向/findAll/{name}发送GET请求。

原理:Spring Cloud应用在启动时,Feign会扫描标有@FeignClient注解的接口,生成代理,并注册到Spring容器中。生成代理时Feign会为每个接口方法创建一个RequetTemplate对象,该对象封装了HTTP请求需要的全部信息,请求参数名、请求方法等信息都是在这个过程中确定的,Feign的模板化就体现在这里。

(3)启动类上添加注解

[Java] 纯文本查看 复制代码
?

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.ace.cache.EnableAceCache;

@EnableEurekaClient
@SpringBootApplication
@ComponentScan(basePackages={"com.guorenpcic.grecar","com.gr.framework.security.common"})
// 开启druid监控
@ServletComponentScan("com.guorenpcic.grecar.config.druid")
// 开启事务
@EnableTransactionManagement
// 开启熔断监控
@EnableCircuitBreaker
//// 开启服务鉴权
@EnableFeignClients({"com.gr.framework.security.auth.client.feign","com.guorenpcic.grecar.feign"})
@EnableAceCache
public class GrECarApplication {

public static void main(String[] args) {
    SpringApplication.run(GrECarApplication.class, args);
}

}
(4)配置文件

[Java] 纯文本查看 复制代码
?

logging:

level:
     com:guorenpcic.grecar: INFO
     com.guorenpcic.grecar.mapper: DEBUG
     test: INFO

spring:

application:
    name: gr-ecar-app
jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    default-property-inclusion: non_empty
datasource:
    name: test
    #测试环境
    url: jdbc:mysql://xxxxxx:3306/gr_ecar?useUnicode=true&characterEncoding=UTF8
    username: xxx
    password: xxx
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
rabbitmq:
    host: xx.xx.xx.xx
    port: xxx
    username: xxxx
    password: password

配置数据库

mybatis:

basepackage: com.guorenpcic.grecar.mapper
xmlLocation: classpath:mapper/**/*.xml

server:

port: 21113

配置spring cloud 服务发现

eureka:

instance:
    statusPageUrlPath: /info
    healthCheckUrlPath: /health
    # docker 部署开启
    prefer-ip-address: true
    ip-address: 10.75.5.10
client:
    serviceUrl:

defaultZone: http://xxxxxxxx:xxxx/eureka/

        defaultZone: http://xxxxxxxx:8761/eureka/
        #开发环境

defaultZone: http://xx.xx.xx.xx:${EUREKA_PORT:8001}/eureka/

配置swagger

swagger:

basepackage: com.guorenpcic.grecar.security.common.rest
service:
    name: 车险出单平台后端应用
    description: 车险出单平台后端应用服务接口文档
    developer: dc

redis-cache 相关

redis:

pool:
     maxActive: 300
     maxIdle: 100
     maxWait: 1000
host: xxxxxxxxx
port: xxxx
password:
timeout: 2000
# 服务或应用名
sysName: gr-ecar
enable: true
database: 0

配置用户认证和服务认证信息

auth:
serviceId: gr-auth
user:

token-header: Authorization

client:

id: gr-ecar-app
secret: 9zRzsRos
token-header: client-token

hystrix:

command:
    default:
        execution:
            timeout:
                enabled: false

ribbon:

ReadTimeout: 120000
ribbon:
    ConnectTimeout: 30000

【方法2】

2、微服务之间的调用,不用feignClient,直接用http想调用其他项目的接口(不是微服务之间也能调用,如Springcloud调servlet方法)

[Java] 纯文本查看 复制代码
?

public static String validateIdentity(String url, String jsonString) throws Exception {

    SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
    CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
    // DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonString,"gbk");// 解决中文乱码问题
    entity.setContentEncoding("gbk");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    System.out.println(jsonString);
    HttpResponse httpResponse = httpClient.execute(httpPost);
    
    String resultJson = EntityUtils.toString(httpResponse.getEntity());
    resultJson = URLDecoder.decode(resultJson, "UTF-8");
    System.out.println(resultJson);
    return resultJson;
}

[Java] 纯文本查看 复制代码
?
1
2
String responseJson = HttpUtil.validateIdentity(BASE_URL+"comCode/comCodeApi",JSON.toJSONString(initializationQueryVo));

        initializationResponseVo = JSON.parseObject(responseJson, InitializationResponseVo.class);

扩展调用:

[Java] 纯文本查看 复制代码
?

private List<PrpDunitMaintenanceSHDto> queryPrpDunitMaintenanceSH(SelectTagListDto selectTagListDto) throws Exception {

       String url  = GR_DMS_URL+"/prpDunitMaintenanceSH/queryPrpDunitMaintenanceSH";//另一个系统的url
       LOGGER.info("‘’‘’‘’‘’‘’‘’‘’‘’‘’决策单元地址:"+ url);//测试所用
       String res = HttpClientUtil.validateIdentity(url, JSONObject.toJSONString(selectTagListDto),"UTF-8");//http方式调用,在调接口成功后一直不识别中文,注意要加上入参的编码格式
       LOGGER.info("‘’‘’‘’‘’‘’‘’‘’‘’‘’决策单元结果:"+res );//测试所用
       List<PrpDunitMaintenanceSHDto> prpdunitMaintenanceSHDtoList = JSONObject.parseArray(res,PrpDunitMaintenanceSHDto.class);
       return prpdunitMaintenanceSHDtoList;
 }

[Java] 纯文本查看 复制代码
?

public static String validateIdentity(String url, String jsonString,String bianma) throws Exception {

    SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
    CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
    //设置超时时间 by chenxiaohui 20180721 beign
    //RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();//设置请求和传输超时时间
    //设置超时时间 by chenxiaohui 20180721 end
    // DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonString,bianma);// 解决中文乱码问题
    entity.setContentEncoding("gbk");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    /** 设置超时时间 by chenxiaohui 20180721 beign  */
    //httpPost.setConfig(requestConfig);
    /** 设置超时时间 by chenxiaohui 20180721 end  */
    System.out.println(jsonString);
    HttpResponse httpResponse = httpClient.execute(httpPost);
    String resultJson = EntityUtils.toString(httpResponse.getEntity());
    resultJson = URLDecoder.decode(resultJson, "UTF-8");//反参的编码格式
    System.out.println("======================"+resultJson);//获得核心的计算保费反参
    return resultJson;
}

2018101516411130.png (81.03 KB, 下载次数: 1)

2018101516411130.png

评论

暂无评论