SpringCloud Alibaba入门案例环境

开课吧樵夫2021-12-08 15:16

  在完成了SpringCloud Alibaba的基本知识讲解之后,我们需要搭建一个SpringCloud Alibaba的入门案例环境。由于在——SpringCloud Netflix入门,这篇文章中已经搭建过一次父工程+提供者&消费者项目,所以本篇的入门案例环境不再对IDEA的操作进行赘述。

  创建父工程

  创建父工程并实现一个消费者调用提供者的实例,为后续SpringCloud Alibaba项目的运行提供测试环境。

  使用了MySQL数据库

  使用Spring Data JPA作为持久层技术

  没有用到Spring Cloud

  创建familycloud-alibaba项目作为本教程的父工程。

  修改pom.xml文件

  删除一些项目自动生成的不需要的依赖并对后续所要使用的依赖进行版本管理:

<?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>
    <packaging>pom</packaging>

    <modules>
        <module>provider-8081</module>
        <module>consumer-8080</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.familycloud-alibaba</groupId>
    <artifactId>familycloud-alibaba</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>familycloud-alibaba</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <druid.version>1.1.10</druid.version>
        <mysql.version>8.0.18</mysql.version>
        <lombok.version>1.18.20</lombok.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

  创建提供者工程provider-8081

  添加需要的依赖

  将提供者工程需要的依赖添加到pom.xml文件中。

<?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>familycloud-alibaba</artifactId>
        <groupId>com.familycloud-alibaba</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider-8081</artifactId>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

  定义实体类

  定义实体类的同时,使用@Entity注解在数据库中自动创建Pets表。

package com.javafamily.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

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

@Data
// 声明当前类为实体类
@Entity
// 作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "fieldHandler"})
public class Pets {
    //声明当前属性为主键id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//配置主键生成策略:使用数据库主键自增策略
    private Integer id;
    private String name;
}

  延迟加载

// 当前要访问id为5的对象,底层应该调用select语句,但是此时没有真正调用

//所以这里的pets实际是一个javasist动态代理对象,是空的,如果被数据转换将会报错

Pets pets = service.findById(5);

// 访问详情时才会真正调用select语句

String name = pets.getName();

  因此需要使用@JsonIgnoreProperties标签将延迟加载关闭。

  定义Repository接口继承JpaRepository使该接口提供JPA的相关功能:

package com.javafamily.repository;

import com.javafamily.bean.Pets;
import org.springframework.data.jpa.repository.JpaRepository;

// 第一个泛型是,当前Repository所操作的对象的类型
// 第二个泛型是,当前Repository所操作的对象的id类型
public interface PetsRepository extends JpaRepository<Pets, Integer> {
}

  JpaRepository对关系型数据库进行了抽象封装,继承了 PagingAndSortingRepository 类的所有方法和QueryByExampleExecutor的相关方法。JpaRepository的实现类是SimpleJpaRepository。

  支持了 QueryByExample、批量删除、提高删除效率、手动刷新数据库的更改方法,将默认实现的查询结果变成List。

  定义service接口

package com.javafamily.service;

import com.javafamily.bean.Pets;

import java.util.List;

// 业务层接口
public interface PetsService {
    boolean savePets(Pets pets);

    boolean removePetsById(int id);

    boolean modifyPets(Pets pets);

    Pets getPetsById(int id);

    List<Pets> listAllPets();
}

  service实现类(增删改查)

package com.javafamily.service;

import com.javafamily.bean.Pets;
import com.javafamily.repository.PetsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PetsServiceImpl implements PetsService {
    @Autowired
    private PetsRepository repository;

    @Override
    public boolean savePets(Pets pets) {
        Pets obj = repository.save(pets);
        if (obj != null) {
            return true;
        }
        return false;
    }

    @Override
    public boolean removePetsById(int id) {
        if (repository.existsById(id)) {
            repository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean modifyPets(Pets pets) {
        Pets obj = repository.save(pets);
        if (obj != null) {
            return true;
        }
        return false;
    }

    @Override
    public Pets getPetsById(int id) {
        if (repository.existsById(id)) {
            return repository.getOne(id);
        }
        Pets pets = new Pets();
        pets.setName("dog");
        return pets;
    }

    @Override
    public List<Pets> listAllPets() {
        return repository.findAll();
    }
}

  定义处理器

package com.javafamily.controller;

import com.javafamily.bean.Pets;
import com.javafamily.service.PetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 提供者Controller,对外提供接口
@RequestMapping("/provider/pets")
@RestController
public class PetsController {
    @Autowired
    private PetsService service;

    // 新增
    @PostMapping("/save")
    public boolean saveHandle(@RequestBody Pets pets) {
        return service.savePets(pets);
    }

    // 删除
    @DeleteMapping("/del/{id}")
    public boolean deleteHandle(@PathVariable("id") int id) {
        return service.removePetsById(id);
    }

    // 修改
    @PutMapping("/update")
    public boolean updateHandle(@RequestBody Pets pets) {
        return service.modifyPets(pets);
    }

    // 根据id查询
    @GetMapping("/get/{id}")
    public Pets getHandle(@PathVariable("id") int id) {
        return service.getPetsById(id);
    }

    // 查询列表
    @GetMapping("/list")
    public List<Pets> listHandle() {
        return service.listAllPets();
    }
}

  修改配置文件

server:
  port: 8081

spring:
  # 配置spring data jpa
  jpa:
    # 指定是否在spring容器启动时创建表,默认false
    generate-ddl: true
    # 指定在控制台是否显示SQL语句,默认false
    show-sql: true
    # 指定应用重启后不重新更新表内容
    hibernate:
      ddl-auto: none
  # 配置数据源
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cloudfamily?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

# 配置日志
logging:
  pattern:
    console: level-%level %msg%n

  level:
    root: info
    org.hibernate: info
    # 在show-sql为true时显示SQL中的动态参数值
    org.hibernate.type.descriptor.sql.BasicBinder: trace
    # 在show-sql为true时显示查询结果
    org.hibernate.hql.internal.ast.exec.BasicExecutor: trace
    com.abc: debug

  启动类

package com.javafamily;

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

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

  创建消费者工程consumer-8080

  与创建提供者工程的步骤相同,创建消费者工程,添加需要的依赖:

<?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>familycloud-alibaba</artifactId>
        <groupId>com.familycloud-alibaba</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>consumer-8080</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

  定义实体类

package com.javafamily.bean;

import lombok.Data;

@Data
public class Pets {
    private Integer id;
    private String name;
}

  定义处理器

package com.javafamily.controller;

import com.javafamily.bean.Pets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer/pets")
public class PetsController {
    //注入RestTemplate模板对象
    //RestTemplate  用来发送Http请求,HttpUrlConnection、HttpClient、OkHttp
    @Autowired
    private RestTemplate restTemplate;

    // 配置请求地址:硬编码,将配置信息写死在代码中
    // 怎么才能不硬,写在配置文件中、配置中心中
    private static final String SERVICE_PROVIDER = "http://localhost:8081";

    //跨服务新增
    @PostMapping("/save")
    public boolean saveHandle(@RequestBody Pets pets) {
        String url = SERVICE_PROVIDER + "/provider/pets/save";
        // TODO 问题:消费者直连提供者行不行?
        // 结论:不行
        Boolean result = restTemplate.postForObject(url, pets, Boolean.class);
        return result;
    }

    //跨服务根据id删除
    @DeleteMapping("/del/{id}")
    public void deleteHandle(@PathVariable("id") int id) {
        String url = SERVICE_PROVIDER + "/provider/pets/del/" + id;
        restTemplate.delete(url);
    }

    //跨服务修改
    @PutMapping("/update")
    public void updateHandle(@RequestBody Pets pets) {
        String url = SERVICE_PROVIDER + "/provider/pets/update";
        restTemplate.put(url, pets, Boolean.class);
    }

    //跨服务根据id查询
    @GetMapping("/get/{id}")
    public Pets getHandle(@PathVariable("id") int id) {
        String url = SERVICE_PROVIDER + "/provider/pets/get/" + id;
        Pets pets = restTemplate.getForObject(url, Pets.class);
        return pets;
    }

    //跨服务根据列表查询
    @GetMapping("/list")
    public List<Pets> listHandle() {
        String url = SERVICE_PROVIDER + "/provider/pets/list/";
        List list = restTemplate.getForObject(url, List.class);
        return list;
    }
}

  定义PetsConfigure容器类

package com.javafamily;

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

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

  RestTemplate提供了常见的REST请求方案的模版(GET、POST、PUT、DELETE)

  RestTemplate继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作。

  启动类

package com.javafamily;

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

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

  至此完成了SpringCloud Alibaba的入门案例环境搭建。

  gitee:

  https://gitee.com/javainfamily/spring-cloud-alibaba

 

  以上就是开课吧小编为大家整理发布的“SpringCloud Alibaba入门案例环境”一文,更多相关内容尽在开课吧广场Java教程频道。

SpringCloud Alibaba入门案例环境

免责声明:本站所提供的内容均来源于网友提供或网络搜集,由本站编辑整理,仅供个人研究、交流学习使用。如涉及版权问题,请联系本站管理员予以更改或删除。
有用
分享