Java tutorial
/******************************************************************************* * Copyright (c) 2005, 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package com.xyxy.platform.examples.showcase.demos.hystrix.dependency; import com.xyxy.platform.examples.showcase.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.xyxy.platform.examples.showcase.service.AccountEffectiveService; import com.xyxy.platform.examples.showcase.webservice.rest.RestException; import com.xyxy.platform.examples.showcase.webservice.rest.UserDTO; import com.xyxy.platform.modules.core.mapper.BeanMapper; import com.xyxy.platform.modules.core.utils.Threads; /** * Service?Resource. */ @Controller public class DependencyResourceController { public static final int TIMEOUT = 30000; public static String status = "normal"; @Autowired private AccountEffectiveService accountService; /** * ????30? */ @RequestMapping(value = "/hystrix/resource/{id}", method = RequestMethod.GET) @ResponseBody public UserDTO getUser(@PathVariable("id") Long id) { // . if ("normal".equals(status)) { return handleRequest(id); } // 30?. if ("timeout".equals(status)) { Threads.sleep(TIMEOUT); return handleRequest(id); } // ?. if ("server-error".equals(status)) { throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, "Server Exception"); } // if ("bad-request".equals(status)) { throw new RestException(HttpStatus.BAD_REQUEST, "Client send a bad request"); } return null; } private UserDTO handleRequest(Long id) { User user = accountService.getUser(id); UserDTO dto = BeanMapper.map(user, UserDTO.class); dto.setTeamId(user.getTeam().getId()); return dto; } }