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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章