5.创建工程
1、项目整体架构:
common:
service
consumer:
eureka:
2.代码:
service代码
UserController :
package com.lucas.service.web;
import com.lucas.service.service.CountryService;
import com.zpark.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Author Lucas
* @Date 2019/12/17 14:13
* @Version 1.0
*/
@RestController
@RequestMapping("/")
public class UserController {
@Autowired
CountryService countryService;
// @RequestMapping("/{id}")
// public User selectUser(@PathVariable("id") Long id) {
// return userService.queryById(id);
// }
@RequestMapping(value = {"findall"})
public String findAll() {
List<Country> countries = countryService.queryAll();
StringBuilder sb = new StringBuilder();
for (Country country: countries) {
sb.append(country.toString());
}
return sb.toString();
}
}
CountryService
package com.lucas.service.service;
import com.zpark.model.Country;
import java.util.List;
/**
* @Author Lucas
* @Date 2019/12/17 14:12
* @Version 1.0
*/
public interface CountryService {
public List<Country> queryAll();
}
CountryServiceImpl
package com.lucas.service.service;
import com.lucas.service.mapper.CountryMapper;
import com.zpark.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Author Lucas
* @Date 2019/12/17 14:16
* @Version 1.0
*/
@Service
public class CountryServiceImpl implements CountryService {
@Autowired
private CountryMapper countryMapper;
@Override
public List<Country> queryAll() {
return countryMapper.selectAll();
}
}
CountryMapper
package com.lucas.service.mapper;
import com.zpark.model.Country;
import tk.mybatis.mapper.common.Mapper;
/**
* @Author Lucas
* @Date 2019/12/17 14:12
* @Version 1.0
*/
public interface CountryMapper extends Mapper<Country> {
}
service的配置文件
application.yml
server:
port: 8081
servlet:
context-path: /
spring:
datasource:
url: jdbc:mysql://localhost:3306/frame?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: lucas
driver-class-name: com.mysql.cj.jdbc.Driver
thymeleaf:
cache: false
application:
name: user-service
mybatis:
type-aliases-package: com.zpark.model
configuration:
map-underscore-to-camel-case: true
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka,http://localhost:10087/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
service的porm:
<?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>cloud-demo</artifactId>
<groupId>com.lucas</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>user-service</artifactId>
<!--添加依赖-->
<dependencies> <!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <!--mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<artifactId>user-common</artifactId>
<groupId>com.lucas</groupId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.2.RELEASE</version><!--服务器有可不写-->
</dependency>
</dependencies>
</project>
Consumer代码:
ConsumerController
package com.lucas.consumer.controller;
import com.zpark.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @Author Lucas
* @Date 2019/12/18 11:04
* @Version 1.0
*/
@RestController
@RequestMapping("/")
public class ConsumerController {
private String SERVICEURL = "http://localhost:8081/findall";
@Autowired
RestTemplate template;
@Autowired
DiscoveryClient discoveryClient;
@RequestMapping("findall")
public String findAll() {
List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
ServiceInstance instance = instances.get(0);
String host = instance.getHost();
int port = instance.getPort();
// return template.getForObject(SERVICEURL, String.class);
String urlByEureka = "http://" + host + ":" + port + "/findall";
return template.getForObject(urlByEureka, String.class);
}
}
ConsumerController3
package com.lucas.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @Author Lucas
* @Date 2019/12/18 17:53
* @Version 1.0
*/
@RestController
@RequestMapping("/")
public class ConsumerController3 {
@Autowired
RestTemplate restTemplate;
@Autowired
LoadBalancerClient loadBalancerClient;
@RequestMapping("findall2")
public String findAll() {
ServiceInstance instance = loadBalancerClient.choose("user-service");
String host = instance.getHost();
int port = instance.getPort();
// return template.getForObject(SERVICEURL, String.class);
String urlByEureka = "http://" + host + ":" + port + "/findall";
return restTemplate.getForObject(urlByEureka, String.class);
}
@RequestMapping("findall3")
public String findAll2() {
return restTemplate.getForObject("http://user-service/findall",String.class);
}
@RequestMapping("findall4")
public String findAll3() {
ResponseEntity<String> forEntity = restTemplate.getForEntity("http://user-service/findall", String.class);
HttpStatus statusCode = forEntity.getStatusCode();
int statusCodeValue = forEntity.getStatusCodeValue();
HttpHeaders headers = forEntity.getHeaders();
String body = forEntity.getBody();
StringBuilder result = new StringBuilder();
result.append("responseEntity.getBody():").append(body).append("<hr>")
.append("responseEntity.getStatusCode():").append(statusCode).append("<hr>")
.append("responseEntity.getStatusCodeValue():").append(statusCodeValue).append("<hr>")
.append("responseEntity.getHeaders():").append(headers).append("<hr>");
return result.toString();
}
}
启动类:ConsumerApplication
package com.lucas.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @Author Lucas
* @Date 2019/12/18 10:39
* @Version 1.0
*/
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
配置文件:yml
server:
port: 8083
spring:
datasource:
url: jdbc:mysql://localhost:3306/frame?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: lucas
driver-class-name: com.mysql.cj.jdbc.Driver
thymeleaf:
cache: false
application:
name: user-consumer
cloud:
loadbalancer:
retry:
enabled: true # 开启Spring Cloud的重试功能
user-service:
ribbon:
ConnectTimeout: 250 # Ribbon的连接超时时间
ReadTimeout: 1000 # Ribbon的数据读取超时时间
OkToRetryOnAllOperations: true # 是否对所有操作都进行重试
MaxAutoRetriesNextServer: 1 # 切换实例的重试次数
MaxAutoRetries: 1 # 对当前实例的重试次数
mybatis:
type-aliases-package: com.zpark.model
configuration:
map-underscore-to-camel-case: true
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka,http://localhost:10087/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
porm:
<?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>cloud-demo</artifactId>
<groupId>com.lucas</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>user-consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<artifactId>user-common</artifactId>
<groupId>com.lucas</groupId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.2.RELEASE</version><!--版本报错加-->
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
Eureka代码:
启动类:EurekaServerApplication
package com.lucas.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @Author Lucas
* @Date 2019/12/18 14:14
* @Version 1.0
*/
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
yml:
server:
port: 10086
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
spring:
application:
name: eureka-server
common代码:
Country
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 abel533@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.zpark.model;
import org.apache.ibatis.type.JdbcType;
import tk.mybatis.mapper.annotation.ColumnType;
import javax.persistence.Id;
import java.io.Serializable;
/**
* Description: Country
* Author: liuzh
* Update: liuzh(2014-06-06 13:38)
*/
public class Country implements Serializable {
private static final long serialVersionUID = 6569081236403751407L;
@Id
@ColumnType(jdbcType = JdbcType.BIGINT)
private Long id;
private String countryname;
private String countrycode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountryname() {
return countryname;
}
public void setCountryname(String countryname) {
this.countryname = countryname;
}
public String getCountrycode() {
return countrycode;
}
public void setCountrycode(String countrycode) {
this.countrycode = countrycode;
}
@Override
public String toString() {
return "Country{" +
"id=" + id +
", countryname='" + countryname + '\'' +
", countrycode='" + countrycode + '\'' +
'}';
}
}
整个项目porm:
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lucas</groupId>
<artifactId>cloud-demo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>user-service</module>
<module>user-consumer</module>
<module>user-common</module>
<module>eureka-server</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath></relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
<mapper.starter.version>2.0.3</mapper.starter.version>
<mysql.version>8.0.15</mysql.version>
</properties>
<dependencyManagement>
<dependencies> <!-- 引入sprngcloud的pom -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> <!-- 通用mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency> <!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies> <!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>