Microservices use RestTemplate for service calls

In a microservice project, when a service calls other service methods, feign is usually used to call, because the call is relatively simple and direct, and it can be done through annotations and some simple operations. Here, we mainly make a call to the service through RestTemplate Simple logging.

Table of contents

Add configuration class

Concrete operation

Add annotations to the startup class

Add configuration class

First, you need to inject the RestTemplate object, which needs to be configured in the configuration class.

@Configuration
public class Config {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    
}

Concrete operation

Inject the RestTemplate and DiscoveryClient classes into the implementation class , and then use the DiscoveryClient to obtain service information, such as service address, service port, etc., and then use the RestTemplate to implement the call operation. The specific code is as follows.

service provider

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;


    @GetMapping ("/updateGoods/{id}")
    public R updateGoods(@PathVariable Integer id){
        return goodsService.updateGoods(id);
    }


}

service consumer

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public R insertOrder(Order order){
        //根据服务名去获取服务信息
        ServiceInstance service = discoveryClient.getInstances("goods-service").get(0);
        //根据服务名去获取服务信息
        ServiceInstance service2 = discoveryClient.getInstances("coupon-service").get(0);
        //获取服务地址
        String url = service.getHost() + ":" + service.getPort();
        String url2 = service2.getHost() + ":" + service2.getPort();
        System.out.println("---------------调用商品服务进行库存更新--------------------");
        //调用商品服务
        Object forObject = restTemplate.getForObject("http://" + url + "/goods/updateGoods/" + order.getGoodsId() + "?id=" + order.getGoodsId(), Object.class);
        Map map = (Map) forObject;
        if (String.valueOf(map.get("code")).equals("201")){
            System.out.println("---------------商品没有库存啦-----------------");
            return R.fail(201,"商品没有库存啦");
        }
        System.out.println("---------------调用商品服务成功-----------------------");
        System.out.println("---------------调用优惠券服务,修改优惠券信息--------------------");
        //调用优惠券服务
        Object forObject1 = restTemplate.getForObject("http://" + url2 + "/coupon/updateCoupon/" + order.getCouponId() + "?id=" + order.getGoodsId(), Object.class);
        Map map2 = (Map)forObject1;
        if (String.valueOf(map2.get("code")).equals("201")){
            System.out.println("---------------优惠券已经使用过了----------------");
            return R.fail(201,"优惠券已经使用过了");
        }
        System.out.println("---------------调用优惠券服务成功-----------------------");
        order.setPrice(order.getGoodsPrice() * order.getCouponDiscount());
        int i = orderMapper.insertOrder(order);
        return i > 0 ? R.ok(order) : R.fail("失败");
    }
}

If you call other service methods and need to return a result, an Object object will be returned. If you need to get the value of the property inside, you can convert it into a Map, and then get the value through get (property name).

Add annotations to the startup class

Finally, you need to add the @EnableDiscoveryClient annotation to the startup class

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableAspectJAutoProxy(exposeProxy = true)
public class OrderApplication {

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

}

Guess you like

Origin blog.csdn.net/qq_50801874/article/details/130593299