Spring boot 内部服务调用

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;  
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值