参考:《Srping Cloud与Docker微服务架构实战 周立著》
微服务构建的是分布式系统,微服务间通过网络进行通信。微服务中使用服务消费者与服务提供者来描述微服务之间的关系
项目的创建和基础结构可以参照前面的SpringBoot基础部分
server:
port: 8881
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3306/micro_user?useUnicode=true&characterEncoding=utf-8&useSSL=true
username : root
password : xda265856
driverClassName : com.mysql.jdbc.Driver
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
ddl-auto: update
show-sql: true
import javax.persistence.*;
@Entity
@Table(name = "tb_user")
public class ServiceUser {
//设置主键并且设置主键为自增
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private long userId;
@Column(name = "user_name")
private String username;
@Column(name = "user_password")
private String password;
@Column(name = "student_age")
private int age;
//getter and setter
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.virtue.pojo.ServiceUser;
@Repository
public interface UserRepository extends JpaRepository<ServiceUser, Long> {
}
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@ResponseBody
@RequestMapping(value = "/users", method = {RequestMethod.GET})
public List<ServiceUser> showUsers(){
List<ServiceUser> students = userRepository.findAll();
return students;
}
}
http://127.0.0.1:8881/users
可看到如下数据:
public class ServiceUser {
private long userId;
private String username;
private String password;
private int age;
//getter and setter
}
@Controller
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@ResponseBody
@RequestMapping(value = "/movie/users", method = {RequestMethod.GET})
public List<ServiceUser> listUsers(){
return this.restTemplate.getForObject("http://127.0.0.1:8881/users",List.class);
}
}
报错信息
Description:
Field restTemplate in org.virtue.controller.MovieController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
@Controller
public class MovieController {
//
@Bean
RestTemplate loadBalancedRestTemplate() {
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
@ResponseBody
@RequestMapping(value = "/movie/users", method = {RequestMethod.GET})
public List<ServiceUser> listUsers(){
return this.restTemplate.getForObject("http://127.0.0.1:8881/users",List.class);
}
}
compile("org.springframework.boot:spring-boot-starter-actuator")
http://127.0.0.1:8880/actuator
可访问所有的endpointshttp://127.0.0.1:8880/actuator/health