iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Springboot 内部服务调用方式
  • 577
分享到

Springboot 内部服务调用方式

2024-04-02 19:04:59 577人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录Eureka注册的服务之间互相调用1.请求方2.接收方多模块化,服务间调用的坑问题背景解决办法Eureka注册的服务之间互相调用 1.请求方 启动类添加注解,扫描Eureka 中

Eureka注册的服务之间互相调用

1.请求方

启动类添加注解,扫描Eureka 中的全部服务

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class LoginServiceApplication {    
    public static void main(String[] args) {
        new springApplicationBuilder(LoginServiceApplication.class).WEB(true).run(args);
    }    
}

pom.xml 添加包 (版本号 根据实际选择)

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

创建接口类

@FeignClient(name="hello-service") //spring service name
public interface FeignVehicle {
    
    @RequestMapping(value="/hello", method = RequestMethod.GET)
    @ResponseBody
    public List<Map> hello(@RequestParam Map<String,String> params);
}

实现类注入此接口类

@Autowired
FeignVehicle feignVehicle;

使用的时候直接按照正常调用方式即可

Map<String,String> map = new HashMap<String, String>();
feignVehicle.hello(map);

跨服务调用的时候出现token信息取不到,在发送方添加拦截器

@Configuration
public class FeignConfiguration {
 
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) { 
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();
                httpservletRequest request = attributes.getRequest();  //当前服务token
 
                template.header("Authorization","Bearer " + request.getSession().getId()); //template 接收请求方token
            } 
        };
    }
}

2.接收方

请求 启动类

@SpringBootApplication
@EnableEurekaClient
public class HelloServiceApplication {    
    public static void main(String[] args) {
        new SpringApplicationBuilder(HelloServiceApplication.class).web(true).run(args);
    }    
}

请求Controller

@Controller
@RequestMapping("/hello")
public class HelloController {    
    @RequestMapping(value="/hello",method = RequestMethod.GET)
    @ResponseBody
    public List<Map> hello(@RequestParam Map<String, String> queryParam) {
        return null;  
    }
}

多模块化,服务间调用的坑

问题背景

  • product 服务作为服务端,提供了一个 对外通信Fegin接口 ProductClient,放在了com.imooc.product.client jar包下
  • order 服务作为客户端,直接引用上面的jar,使用 ProductClient ,启动主类后报下图错误:

解决办法

多模块化时,应该在order主类上添加下面圈出来的注解,这样启动后就能扫描这个包。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Springboot 内部服务调用方式

本文链接: https://www.lsjlt.com/news/142458.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作