搭建商品服务,并将服务注册到注册中心
一:创建SpringBoot应用,增加服务注册和发现依赖
项目架构
二:模拟商品信息
实体类Product
public class Product implements Serializable {
public Product(int id,String name,int price,int store){
this.id=id;
this.name=name;
this.price=price;
this.store=store;
}
/**
* id
*/
private int id;
/**
* 商品名称
*/
private String name;
/**
* 价格
*/
private int price;
/**
* 库存
*/
private int store;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getStore() {
return store;
}
public void setStore(int store) {
this.store = store;
}
}
三:开发商品列表接口,商品详情接口。数据存储在Map集合中
此处不连接数据库做复杂查询操作,直接在static初始化数据类似dao层
ProductService接口
public interface ProductService {
/**
* 返回商品列表
*/
List<Product> listProduct();
/**
* 根据id查找
* @return
*/
Product findById(int id);
}
ProductServiceImpl实现类
@Service
public class ProductServiceImpl implements ProductService {
//这里就不连接数据库过多操作了,直接在初始化附加数据
//这里Map相当于dao层
private static Map<Integer,Product> daoMap = new HashMap<>();
static {
Product p1 = new Product(1,"iphone4s",9999,10);
Product p2 = new Product(2,"冰箱",4567,20);
Product p3 = new Product(3,"洗衣机",5678,30);
Product p4 = new Product(4,"椅子",6789,40);
daoMap.put(p1.getId(),p1);
daoMap.put(p2.getId(),p2);
daoMap.put(p3.getId(),p3);
daoMap.put(p4.getId(),p4);
}
@Override
public List<Product> listProduct() {
Collection<Product> collection = daoMap.values();
List<Product> list = new ArrayList<>(collection);
//返回商品列表
return list;
}
@Override
public Product findById(int id) {
return daoMap.get(id);
}
}
ProductController控制层
@RestController
@RequestMapping("/api/v1/product")
public class ProductController {
//注入service
@Autowired
private ProductService productService;
/**
* 获取所有商品列表
* @return
*/
@RequestMapping("list")
public Object list(){
return productService.listProduct();
}
/**
* 根据商品id查找商品详情
* @param id
* @return
*/
@RequestMapping("find")
public Object findById(@RequestParam("id") int id){
return productService.findById(id);
}
}
四:配置文件加入注册中心地址
使用eureka客户端 官方文档:http://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#netflix-eureka-client-starter
server:
port: 8771
#指定注册中心
eureka:
client:
sericeUrl:
defaultZone: http://localhost:8761/eureka/
#服务的名称
spring:
application:
name: product-service
五:启动ProductServiceApplication向注册中心注册服务
核心问题:@EnableEurekaClient
在许多博客文档有在启动类前加@EnableEurekaClient注解,表明开启一个Eureka注册客户端,其实不写也能向注册中心注册服务
在官方文档有写,如果在你的项目类路径下依赖中有加spring-cloud-starter-netflix-eureka-client
则无需添加注解
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
在启动前,先启动Eureka客户端,在上章有讲搭建Eureka客户端。
接口成功访问数据后访问localhost:eureka端口号。显示当前服务及节点数则成功注册
多节点启动服务
点击Edit Configurations
将Allow prarllel run勾选:取消表示在idea只能启动一个
配置好后继续启动即可