My Avatar

licaibo

在JDK改来改去!

SpringCloud构建微服务(三) 服务消费

2017年10月02日 星期一, 发表于 海南 东方

如果你对本文有任何的建议或者疑问, 可以在 这里给我提 Issues, 谢谢! :)

本节基于前面搭建的eureka注册中心和config配置中心,要搭建一个服务提供者并集成mybatis用于数据查询,mysql配置从配置中心进行加载,搭建一个服务消费者对提供者进行调用。配置的加载如下图

cmd-markdown-logo

(一) 服务提供者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server:
  port: 8081

spring:
  cloud:
    config:
      uri: http://localhost:${config.port:5555}
      name: service
      profile: ${config.profile:dev}
  application:
    name: provider-server

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8765/eureka/

pagehelper:
  rowBoundsWithCount: true
  pageSizeZero: true
  reasonable: false
1
2
3
4
5
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>
1
2
3
4
5
6
7
@Mapper
public interface UserDao {

    @Select("SELECT * FROM user WHERE NAME = #{name}")
    User selectByName(@Param("name") String name);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{name}")
    public User selectByName(@PathVariable String name) {
        return userService.selectByName(name);
    }

}
1
{"id":1,"name":"lemo","age":21,"address":"海南省海口市"}

(二) 服务消费者

1
2
3
4
5
6
7
8
9
10
11
server:
  port: 8082

spring:
  application:
    name: consumer-server

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8765/eureka/
1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class UserServicer {

    @Autowired
    RestTemplate restTemplate;

    public ResponseEntity<User> selectByName(String name) {
        ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://provider-server/user/{name}" ,User.class,name);
        return responseEntity;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserServicer userServicer;

    @GetMapping("/{name}")
    public User selectByName(@PathVariable String name) {
       return userServicer.selectByName(name).getBody();
    }

}
1
{"id":1,"name":"lemo","age":21,"address":"海南省海口市"}

cmd-markdown-logo