上一篇博客對Eureka的理論知識有一定的瞭解了,那麼實踐出真知,Eureka該怎麼用呢,如何搭建呢?下邊我就一步一步搭建實現下。關於使用Eureka,肯定是需要服務提供者與消費者的,這樣纔會體現Eureka的作用。下邊我就創建3個工程,一個服務提供者(producer-demo),一個服務消費者(consumer-demo),一個註冊中心Eureka工程(eureka-demo).
一、服務提供者
(1)創建一個工程producer-demo
其整體目錄結構如下
(2)導入它需要的依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
(3)配置文件
application.yml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/leyou?serverTimezone=UTC # 連自己的數據庫即可
username: root
password: root
hikari:
maximum-pool-size: 20
minimum-idle: 10
application:
name: producer-service
mybatis:
type-aliases-package: com.eureka.producerdemo.pojo
eureka:
client:
register-with-eureka: true # 是否註冊自己的信息到EurekaServer,默認是true
fetch-registry: false # 是否拉取其它服務的信息,默認是true
service-url: # EurekaServer的地址,現在是自己的地址,如果是集羣,需要加上其它Server的地址。
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true # 當調用getHostname獲取實例的hostname時,返回ip而不是host名稱
ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的話會自己尋找
lease-expiration-duration-in-seconds: 90 # 服務失效時間,默認值90秒(90秒即過期)
lease-renewal-interval-in-seconds: 30 # 服務續約(renew)的間隔,默認爲30秒(也就是30秒一次心跳)
instance-id: ${spring.application.name}:${server.port} # 修改Eureka的Status一列的構成
(4)啓動文件
@SpringBootApplication
@MapperScan("com.eureka.producerdemo.mapper")
@EnableDiscoveryClient
public class ProducerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerDemoApplication.class, args);
}
}
- @SpringBootApplication 是啓動註解
- @MapperScan(“com.eureka.producerdemo.mapper”)是對mapper文件進行掃描
- @EnableDiscoveryClient是將此項目標記爲Eureka客戶端
(5)編寫controller
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("{id}")
public ResponseEntity<User> selectUserById(@PathVariable("id") Long id){
User user = userService.selectUserById(id);
return ResponseEntity.ok(user);
}
}
(6)編寫service
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User selectUserById(Long id) {
User user = userMapper.selectByPrimaryKey(id);
return user;
}
}
(7)編寫mapper
public interface UserMapper extends Mapper<User> {
}
(8)編寫pojo
@Data
@Table(name = "tb_user")
public class User {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 用戶名
private String username;
//手機號
private String phone;
}
- @Data是自動注入getter和setter已構造器方法
- @Table是引入表,與數據庫表對應
(9)結果
直接訪問服務提供者對應的地址
二、服務消費者
(1)創建一個工程consumer-demo
其整體目錄結構如下
(2)導入需要的依賴
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加OkHttp支持 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
(3)配置文件
application.yml
server:
port: 8080
spring:
application:
name: consumer
eureka:
client:
register-with-eureka: false
fetch-registry: true
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
(4)controller
@RestController
@RequestMapping("consumer")
public class ConsumerController {
@Autowired
private UserService userService;
@GetMapping
public List<User> consume(@RequestParam("ids") List<Long> ids){
return userService.querUserByIds(ids);
}
}
(5)service
@Service
public class UserService {
@Autowired
private UserDao userDao;
public List<User> querUserByIds(List<Long> ids){
List<User> users=new ArrayList<>();
for (Long id:ids){
User user = userDao.queryUserById(id);
users.add(user);
}
return users;
}
}
(6)dao
@Component
public class UserDao {
@Autowired
private RestTemplate restTemplate;
// Eureka客戶端,可以獲取到服務實例信息
@Autowired
private DiscoveryClient discoveryClient;
public User queryUserById(Long id){
//String url = "http://localhost:8081/user/" + id;
// 根據服務名稱,獲取服務實例
List<ServiceInstance> instances = discoveryClient.getInstances("producer-service");
ServiceInstance instance = instances.get(0);
String url="http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;
return restTemplate.getForObject(url, User.class);
}
}
(7)pojo
(同上邊的User)與生產者的User一樣
在消費者這裏,如果沒有Eureka註冊中心,則消費者需要記住服務提供者的地址(也就是上邊userDao裏被註釋的【String url = "http://localhost:8081/user/" + id;】這行代碼),原來使用這種的直接寫死的URL進行訪問,就是消費者直接調服務者了,也是可以調通的。 上邊的關於消費者的代碼,是直接針對有Eureka的,如果想直接消費者調服務提供者,不經過Eureka,可以這樣改:@Component
public class UserDao {
@Autowired
private RestTemplate restTemplate;
// Eureka客戶端,可以獲取到服務實例信息
@Autowired
private DiscoveryClient discoveryClient;
public User queryUserById(Long id){
String url = "http://localhost:8081/user/" + id;
// 根據服務名稱,獲取服務實例
// List<ServiceInstance> instances = discoveryClient.getInstances("producer-service");
// ServiceInstance instance = instances.get(0);
// String url="http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;
return restTemplate.getForObject(url, User.class);
}
}
3、註冊中心Eureka
(1)創建一個工程eureka-demo
其整體目錄結構如下
(2)導入需要的依賴
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- SpringCloud依賴,一定要放到dependencyManagement中,起到管理版本的作用即可 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
(3)配置文件
application.xml
server:
port: 10086
spring:
application:
name: eureka-server
eureka:
client:
register-with-eureka: false # 是否註冊自己的信息到EurekaServer,默認是true
fetch-registry: false # 是否拉取其它服務的信息,默認是true
service-url: # EurekaServer的地址,現在是自己的地址,如果是集羣,需要加上其它Server的地址。
defaultZone: http://127.0.0.1:${server.port}/eureka
(4)啓動文件
@SpringBootApplication
@EnableEurekaServer
public class EurekaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaDemoApplication.class, args);
}
}
- @SpringBootApplication 啓動註解
- @EnableEurekaServer 代表是Eureka服務端
(5)實現效果
注意
關於這三個工程,要先啓動Eureka,再啓動服務提供者和消費者。因爲服務提供者是註冊在Eureka上的,服務消費者也要從Eureka上拉消息,如果沒有啓動Eureka而先啓動服務提供者,會提示找不到服務的。
關於這篇博客的源碼我已經上傳至CSDN,下載鏈接:https://download.csdn.net/download/cxh6863/12374250