SpringCloud 商城系统搭建之eureka

Spring Cloud 专栏收录该内容
7 篇文章 1 订阅

项目环境

1、IDE:eclipse ,maven
2、操作系统:win10
3、jdk:1.8
4、springboot 2.1.0.RELEASE ,springcloud Greenwich.SR5

SpringCloud对应SpringBoot版本如下:

springcloud 版本序列springboot版本
Greenwich2.1.x
Finchley2.0.x
Edgware1.5.x
Dalston1.5.x

Maven 项目搭建

第一步:创建Maven 项目(supermarker),并在pom.xml 添加相关依赖.

pom.xml 

<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.zzg</groupId>
	<artifactId>supermarker</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<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.SR5</spring-cloud.version>
	</properties>
	
	<dependencies>
		<!--test-->
		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<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>


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

第二步:创建supermarker 项目的子项目(supermarker-eureka),并在pom.xml 添加相关依赖.

<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>
  <parent>
    <groupId>com.zzg</groupId>
    <artifactId>supermarker</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>supermarker-eureka</artifactId>
  	<!-- 添加服务注册中心  -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

Eureka服务发现配置

1、打开supermarker-eureka项目启动类,加上@EnableEurekaServer注解,表明这是个服务注册中心。

package com.zzg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SpringApplication.run(EurekaApplication.class, args);
	}

}

2、打开resources文件夹下的application.properties,添加如下配置

server.port=8081

# 实例名称 名字可以自己定
eureka.instance.hostname=eureka1

# eureka client 信息是否被其他eureka client 发现它的信息
eureka.client.register-with-eureka=false
# 此客户端是否应该从eureka server 获取eureka注册信息
eureka.client.fetch-registry=false

#关闭保护模式
eureka.server.enable-self-preservation=false
#设置清理的间隔时间,毫秒单位(默认是60秒)
eureka.server.eviction-interval-timer-in-ms=1000

eureka.client.serviceUrl.defaultZone=http://localhost:8081/eureka/

3、配置文件修改好后,启动EruekaServerApplication ,访问http://localhost:8081/,看到如下界面代表eureka服务端创建成功。因为没有服务注册到eureka server红框内所有红框内没有服务实例

第三步:创建supermarker 项目的子项目(supermarker-provider),并在pom.xml 添加相关依赖.

pom.xml

<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>
	<parent>
		<groupId>com.zzg</groupId>
		<artifactId>supermarker</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>supermarker-provider</artifactId>

	<!-- 添加服务注册中心 -->
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<!--h2 -->
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!--spring-data-jpa -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<!--lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<!--srping-boot-actuator-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
	</dependencies>
</project>

生产者配置

1、打开supermarker-provider的启动类,在启动类上加上注解@EnableEurekaClient

package com.zzg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class EurekaProviderApplication {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SpringApplication.run(EurekaProviderApplication.class, args);
	}

}

2、打开生产者的application.properties,添加如下配置

server.port=8082
# 生产者应用名称 -
spring.application.name=provider
# 生产者实例名,同一个spring.application.name 名称唯一
eureka.instance.instance-id=provider1
        
eureka.client.register-with-eureka=true
# 和eureka服务器通讯的URL
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/

# 设置心跳的时间间隔(默认是30秒)
eureka.instance.lease-renewal-interval-in-seconds=5
# eureka server 最后一次收到心跳时等待的时间,超时将会移除client(默认是90秒)
eureka.instance.lease-expiration-duration-in-seconds=3

3、创建一个基于H2内存数据库简单查询Controller简单证明生产者能正常访问。

controller:

package com.zzg.controller;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.zzg.dao.UserRepository;
import com.zzg.entity.User;

@RestController
public class UserController {
	@Autowired
	private UserRepository userRepository;
	
	
	@GetMapping("/user/{id}")
    public User findById(@PathVariable Integer id) {
        return userRepository.findOne(new Specification<User>() {
			
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				 List<Predicate> predicates = new ArrayList<Predicate>();
	             // 用户编号
	             predicates.add(criteriaBuilder.equal(root.<Integer> get("useId"), id));
	                
				return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
			}
		}).orElse(null);
    }

}

dao层

package com.zzg.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import com.zzg.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {

}

entity层

package com.zzg.entity;



import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
public class User {
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增长策略
	private Integer useId;
	
	@Column
	private String useName;
	
	@Column
	private String useSex;
	
	@Column
	private Integer useAge;
	
	@Column
	private String useIdNo;
	
	@Column
	private String usePhoneNum;
	
	@Column
	private String useEmail;
	
	@Column
	private Date createTime;
	
	@Column
	private Date modifyTime;
	
	@Column
	private String useState;
}

配置完成之后启动EurekaProviderApplication,通过浏览器访问http://localhost:9001/hi/hello ,出现如下界面证明生产者创建成功

springcloud 集成H2 内存数据库参考文章地址:https://blog.csdn.net/zhouzhiwengang/article/details/111265276

第四步:创建supermarker 项目的子项目(supermarker-consume),并在pom.xml 添加相关依赖.

pom.xml

<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>
	<parent>
		<groupId>com.zzg</groupId>
		<artifactId>supermarker</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>supermarker-consume</artifactId>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<!--srping-boot-actuator -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!--lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
	</dependencies>
</project>

消费者配置

1、在supermarker-consume启动类上加@EnableEurekaClient注解

package com.zzg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class EurekaConsumeApplication {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SpringApplication.run(EurekaConsumeApplication.class, args);
	}

}

2、打开消费者的application.properties,添加如下配置

server.port=8083
spring.application.name=consumer
#
eureka.client.register-with-eureka=false
# 和eureka服务器通讯的URL
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/
eureka.instance.instance-id=consumer1

3、调用生产者
3.1 对于restful调用,springboot提供了RestTemplate,但是我们首先要将RestTemplate对象注入到spring容器中
配置类如下:

package com.zzg.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestConfig {
	@Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

3.2 创建一个UserConsumer 调用生产者

package com.zzg.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.zzg.entity.User;

@RestController
public class UserController {
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping("/user/{id}")
    public User findById(@PathVariable Integer id) {
		return restTemplate.getForObject("http://localhost:8082/user/" + id, User.class);
	}

}

实体对象User

package com.zzg.entity;

import java.util.Date;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class User {
	private Integer useId;
	
	private String useName;
	
	private String useSex;
	
	private Integer useAge;
	
	private String useIdNo;
	
	private String usePhoneNum;
	
	private String useEmail;
	
	private Date createTime;
	
	private Date modifyTime;
	
	private String useState;
}

4、启动EurekaConsumeApplication,浏览器访问http://localhost:8083/user/1,出现如下界面证明消费者创建成功

至此SpringCloud 集成eureka 服务完结。

源码地址:待补充

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值