模擬資料在使用者服務實現簡單的查詢
阿新 • • 發佈:2018-12-15
1 在userService專案 新增service serviceImpl 模擬查詢資料庫
@Service public class UserServiceImpl implements UserService { public static final Map<String,User> resMap = new HashMap<String,User>(); static { User u1= new User("1","張三","zhangsan","1234"); User u2= new User("2","張三1","zhangsan1","1234"); User u3= new User("3","張三2","zhangsan2","1234"); User u4= new User("4","張三3","zhangsan3","1234"); User u5= new User("5","張三4","zhangsan4","1234"); resMap.put("1",u1); resMap.put("2",u2); resMap.put("3",u3); resMap.put("4",u4); resMap.put("5",u5); } @Override public List<User> getList() { Collection<User> collection= resMap.values(); List<User> userList = new ArrayList<User>(collection); return userList; } @Override public User findUser(String id) { return resMap.get(id); } }
2新建controller
@RestController @RequestMapping(value="/api/user/") public class UserController { @Autowired private UserService userService; @RequestMapping(value="list") public Object List(){ return userService.getList(); } @RequestMapping( value="find") public Object findById(@RequestParam("id") String id){ return userService.findUser(id); } }
3 啟動user_service服務測試一下
4 模擬登入login_srvice 呼叫user_service使用者查詢 Feign
新建login_service專案
增加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
5 增加feignClient
FeignClient("USER-SERVICE") // 服務名稱USER-SERVICE
public interface UserFeignClient {
@RequestMapping(method = RequestMethod.GET, value ="/api/user/list")
List<Object> getUserList();
@RequestMapping(method = RequestMethod.GET,value ="/api/user/find")
Object getById(@RequestParam("id") String id);
}
6 新增controller
@RestController
public class LoginController {
@Autowired
private UserFeignClient userFeignClient;
@RequestMapping("/list")
public Object getList(){
return userFeignClient.getUserList();
}
}
7 修改yml檔案
server:
port: 8991
spring:
application:
name: login-service
eureka:
hostname:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
8 檢視註冊中心
8 呼叫login_service的list介面