SpringCloud学习日记(一)服务注册与发现EUREKA配置

当下微服务项目比较火,之前利用业余时间系统的学习了一下,但是公司中没有使用到相关技术,所以时间一长难免会有所遗忘,在此总结一下SpringCloud的常用服务知识,以作备忘。

SpringCloud是基于SpringBoot的一套分布式解决方案,跟国内常用DUBBO框架类似,但是它所提供的解决方案更加全面,基本上都能在官网上找到资料,唯一不好的是,对于英语不好的人来说看起来比较痛苦,今天做为我的SpringCloud相关知识的第一篇博客,主要来讲一下服务注册与发现组件eureka在springcloud项目下的使用。

springcloud的服务注册与发现提供了多种解决方案,像客户端发现组件:eureka和zookeeper;像服务端发现组件conscul+nginx,根据别人以及官方给出的建议,SpringCloud对eureka的支持度最高,是首选,因此优先学习了eureka在SpringCloud项目中使用。

第一步,准备两个SpringBoot项目,其中一个是生产者,另一个是消费者,由于两个项目有重复交叉的依赖使用,因此可以在两个项目的基础上抽出公用依赖做一个父POM项目。

父POM项目配置如下,其中的pom配置如下:



	4.0.0

	com.zdd
	spring-cloud-parent
	0.0.1-SNAPSHOT
	pom

	spring-cloud-parent
	
	
	
		spring-cloud-customer
		spring-cloud-provided
		spring-cloud-eureka
	

	
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.13.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
	
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				Dalston.SR5
				pom
				import
			
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

第二步,生产者创建

pom.xml



	4.0.0

	com.zdd
	spring-cloud-provide
	0.0.1-SNAPSHOT
	jar

	spring-cloud-provide
	Demo project for Spring Boot

	
		com.zdd
		spring-cloud-parent
		0.0.1-SNAPSHOT
		 
	

	
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			com.h2database
			h2
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

application.yml

server:
  port: 7900
spring:
  datasource:
    platform: H2
    data: classpath:data.sql
    schema: classpath:schema.sql
  jpa:
    show-sql: true
    generate-ddl: false
    hibernate:
      ddl-auto: false
logging:
  level:
    root: info
    org.hibernate: info
    org.hibernate.type.descriptor.sql.BasicBinder: trace
    org.hibernate.type.descriptor.sql.BasicExtractor: trace
    com.zdd: debug

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)
);

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);
insert into user(id,username,name,age,balance) values(5,'user5','钱七',20,100.00);

SpringCloudProvideApplication.java(入口启动类)

package com.zdd.springcloudprovide;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringCloudProvideApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringCloudProvideApplication.class, args);
	}
}

User.java(实体类)

package com.zdd.springcloudprovide.entity;

import java.math.BigDecimal;

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

@Entity
public class User {

	@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 id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Short getAge() {
		return age;
	}

	public void setAge(Short age) {
		this.age = age;
	}

	public BigDecimal getBalance() {
		return balance;
	}

	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}
	
	
}

UserRepository(DAO)

package com.zdd.springcloudprovide.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.zdd.springcloudprovide.entity.User;

public interface UserRepository extends JpaRepository{

}

Controller

package com.zdd.springcloudprovide.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 com.zdd.springcloudprovide.entity.User;
import com.zdd.springcloudprovide.repository.UserRepository;

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepositor;
	
	@GetMapping("/simple/{id}")
	public User findById(@PathVariable("id")Long id){
		return this.userRepositor.findOne(id);
	}
}

启动项目,访问http://localhost:7900/simple/1,能正常返回数据表示配置成功。项目使用的内存数据库H2,因为测试功能比较简单,省略了业务层。

第三步,消费者创建

pom.xml



	4.0.0

	com.zdd
	spring-cloud-customer
	0.0.1-SNAPSHOT
	jar

	spring-cloud-customer
	Demo project for Spring Boot

	
		com.zdd
		spring-cloud-parent
		0.0.1-SNAPSHOT
		 
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

application.yml

server:
  port: 7901
user:
  servicePath: http://localhost:7900/simple/

User(实体类跟生产者实体类一致,去掉里面的注解即可)

入口启动类

package com.zdd.springcloudcustomer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SpringCloudCustomerApplication {

	@Bean
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
	
	
	public static void main(String[] args) {
		SpringApplication.run(SpringCloudCustomerApplication.class, args);
	}
}

Controller

package com.zdd.springcloudcustomer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.zdd.springcloudcustomer.entity.User;

@RestController
public class MovieController {

	@Autowired
	private RestTemplate restTemplate;
	
	@Value("${user.servicePath}")
	private String servicePath;
	
	@GetMapping("/movie/{id}")
	public User movie(@PathVariable("id")Long id){
		return this.restTemplate.getForObject(servicePath+id, User.class);
	}
}

启动项目,访问http://localhost:7901/movie/1,能正常返回数据表示创建成功(前提是生产者服务需要在开启状态下)

第四步,创建服务注册与发现中心

pom.xml


	4.0.0

	com.zdd
	spring-cloud-eureka
	0.0.1-SNAPSHOT
	jar

	spring-cloud-eureka
	http://maven.apache.org

	
		com.zdd
		spring-cloud-parent
		0.0.1-SNAPSHOT
	

	
		
			org.springframework.cloud
			spring-cloud-starter-eureka-server
		
		
		
			org.springframework.boot
			spring-boot-starter-actuator
		
		
			org.springframework.boot
			spring-boot-starter-security
		
	

application.yml

server:
  port: 8761
eureka:
  client:
    service-url:
      defaultZone: http://admin:admin@localhost:8761/eureka
    fetch-registry: false
    register-with-eureka: false
security:
  basic:
    enabled: true
  user:
    name: admin
    password: admin

启动入口类:

package com.zdd.spring_cloud_eureka;

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

/**
 * 入口启动类
 *
 */
@SpringBootApplication
@EnableEurekaServer
@EnableDiscoveryClient
public class EurekaApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(EurekaApplication.class, args);
    }
}

启动项目,访问http://localhost:8761/,这时如果项目能正常启动的话就能看到eureka服务器上的注册列表信息了,由于我们还没有在生产方配置使用服务注册,因此当前的注册列表里并没有注册服务。

下面来配置一下生产者的服务发现:

生产者application.yml

server:
  port: 7900
spring:
  datasource:
    platform: H2
    data: classpath:data.sql
    schema: classpath:schema.sql
  jpa:
    show-sql: true
    generate-ddl: false
    hibernate:
      ddl-auto: false
  application:
    name: spring-cloud-provode
logging:
  level:
    root: info
    org.hibernate: info
    org.hibernate.type.descriptor.sql.BasicBinder: trace
    org.hibernate.type.descriptor.sql.BasicExtractor: trace
    com.zdd: debug
eureka:
  client:
    service-url:
      defaultZone: http://admin:admin@localhost:8761/eureka
  instance:
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    prefer-ip-address: true

然后再生产者的启动入口类加上@EnableEurekaClient注解,重启生产者,访问http://localhost:8761/,输入用户名admin,密码admin回车,此时进入服务注册发现中心后台管理页面即可看到生产者已经注册到EurekaServer上。

demo下载地址:

https://download.csdn.net/download/qq_35918388/10434308


你可能感兴趣的:(springboot,springcloud,eureka)