新建一个 provider-user 和consumer-movie, user为服务提供者, movie为服务的消费真, 没有什么难的, 直接上代码
microserver-provider-user:
1, pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-micro</artifactId> <groupId>com.wenbronk</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microserver-provider-user</artifactId> <dependencies> <!--springboot 热部署--> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-devtools</artifactId>--> <!--<optional>true</optional>--> <!--<scope>true</scope>--> <!--</dependency>--> <!-- exclude掉spring-boot的默认log配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- spring-boot的web启动的jar包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 引入log4j2依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <!-- 加上这个才能辨认到log4j2.yml文件 --> <dependency> <!-- 加上这个才能辨认到log4j2.yml文件 --> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- 添加springboot 的健康模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <!--<build>--> <!--<plugins>--> <!--<plugin>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-maven-plugin</artifactId>--> <!--<configuration>--> <!--<!– 如果没有这个, 不生效 –>--> <!--<fork>true</fork>--> <!--</configuration>--> <!--</plugin>--> <!--</plugins>--> <!--</build>--> </project>
2, mianClass
package com.wenbronk.provider.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Created by root on 2017/5/17. */ @SpringBootApplication //@EnableEurekaClient // 只对eureka 可用 @EnableDiscoveryClient // 可用zk, eureka等 public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
添加@EnableDiscoveryClient, 既可以声明为eureka的客户端, 然后通过配置文件注册服务
application.yml
server: port: 7902 spring: # 设置eureka中注册的名称, 全小写, 否则大小写混杂出现问题 application: name: microservice-provider-user jpa: generate-ddl: false show-sql: true hibernate: ddl-auto: none datasource: platform: h2 schema: classpath:schema.sql data: classpath:data.sql logging: level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE com.itmuch: DEBUG eureka: client: serviceUrl: defaultZone: http://wenbronk:[email protected]:8761/eureka healthcheck: enabled: true # 添加注册中心中的ip代替主机名 instance: prefer-ip-address: true instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}} statusPageUrlPath: ${management.context-path}/info healthCheckUrlPath: ${management.context-path}/health
data.sql
insert into user(id,username, name, age, balance) values(1,‘user1‘, ‘张三‘, 20, 100.00); insert into user(id,username, name, age, balance) values(2,‘user2‘, ‘李四‘, 20, 100.00); insert into user(id,username, name, age, balance) values(3,‘user3‘, ‘王五‘, 20, 100.00); insert into user(id,username, name, age, balance) values(4,‘user4‘, ‘马六‘, 20, 100.00);
schema.sql
drop table user if exists; create table user( id bigint generated by default as identity, username varchar(40), name varchar(20), age int(3), balance decimal(10,2), primary key(id) );
然后业务代码:
Repository.java, 此工程使用的是springboot的内嵌数据库
package com.wenbronk.provider.user.repository; import com.wenbronk.provider.user.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { }
User.java
package com.wenbronk.provider.user.entity; import javax.persistence.*; import java.math.BigDecimal; @Entity public class User { public User(Long id, String username) { super(); this.id = id; this.username = username; } public User() { super(); } @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private String name; @Column private Short age; @Column private BigDecimal balance; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Short getAge() { return this.age; } public void setAge(Short age) { this.age = age; } public BigDecimal getBalance() { return this.balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
userController.java
package com.wenbronk.provider.user.controller; import com.google.common.collect.Lists; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import com.wenbronk.provider.user.entity.User; import com.wenbronk.provider.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController public class UserController { @Autowired private UserRepository userRepository; @Autowired private EurekaClient eurekaClient; /** * 为Netflix不具体的发现客户端提供简单的API */ @Autowired private DiscoveryClient discoveryClient; @GetMapping("/simple/{id}") public User findById(@PathVariable Long id) { return this.userRepository.findOne(id); } /** * 发现其他服务, 返回一个url:port * @return */ @GetMapping("/eureka-instance") public String serviceUrl() { InstanceInfo eureka = this.eurekaClient.getNextServerFromEureka("microservice-provider-user", false); return eureka.getHomePageUrl(); } @GetMapping("/instance-info") public ServiceInstance showInfo() { ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance(); return localServiceInstance; } @PostMapping("/user") public User postUser(@RequestBody User user) { return user; } // 该请求不会成功 @GetMapping("/get-user") public User getUser(User user) { return user; } @GetMapping("list-all") public List<User> listAll() { ArrayList<User> list = Lists.newArrayList(); User user = new User(1L, "zhangsan"); User user2 = new User(2L, "zhangsan"); User user3 = new User(3L, "zhangsan"); list.add(user); list.add(user2); list.add(user3); return list; } }
microserver-consumer-user
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-cloud-micro</artifactId> <groupId>com.wenbronk</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microserver-consumer-movie</artifactId> <dependencies> <!--springboot 热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!-- exclude掉spring-boot的默认log配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- spring-boot的web启动的jar包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 引入log4j2依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <!-- 加上这个才能辨认到log4j2.yml文件 --> <dependency> <!-- 加上这个才能辨认到log4j2.yml文件 --> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- 添加springboot 的健康模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!-- 如果没有这个, 不生效 --> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>
application.yml
server: port: 7901 spring: # 设置eureka中注册的名称, 全小写, 否则大小写混杂出现问题 application: name: microservice-consumer-movie logging: level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE com.itmuch: DEBUG eureka: client: serviceUrl: defaultZone: http://wenbronk:[email protected]:8761/eureka # 添加注册中心中的ip代替主机名 instance: prefer-ip-c: true instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}} statusPageUrlPath: ${management.context-path}/info healthCheckUrlPath: ${management.context-path}/health
mainClass.java
package com.wenbronk.consumer.movie; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; /** * 启动类 * Created by root on 2017/5/18. */ @SpringBootApplication @EnableEurekaClient public class MovieApplication { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(MovieApplication.class, args); } }
user.java
package com.wenbronk.consumer.movie.entity; import java.math.BigDecimal; public class User { private Long id; private String username; private String name; private Short age; private BigDecimal balance; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Short getAge() { return this.age; } public void setAge(Short age) { this.age = age; } public BigDecimal getBalance() { return this.balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
movieController.java
package com.wenbronk.consumer.movie.controller; import com.wenbronk.consumer.movie.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * Created by root on 2017/5/18. */ @RestController public class MovieController { @Autowired private RestTemplate restTemplate; @RequestMapping("/movie/{id}") public User findById(@PathVariable Long id) { return restTemplate.getForObject("http://localhost:7900/simple/" + id, User.class); } }
服务开启顺序为: eureka, user, movie, 之后通过浏览器就可以调用movie中的服务, 在console中可看到movie正确调用了user中的服务
时间: 2024-10-13 14:10:54