从零创建微服务(一)

从零搭建springcloud微服务(一)

  1. 新建项目,如下图所示。

从零创建微服务(一)_第1张图片
从零创建微服务(一)_第2张图片

选择依赖。

从零创建微服务(一)_第3张图片

然后next,最后finish完成。

2.新建一个module(user-service)。

从零创建微服务(一)_第4张图片
从零创建微服务(一)_第5张图片
一直next。

3.这里我们使用mybatis逆向工程插件。添加插件依赖。

 <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.2version>
                <configuration>
                    
                    <configurationFile>src/main/resources/generator.xmlconfigurationFile>
                    <verbose>trueverbose>
                    <overwrite>trueoverwrite>
                configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifactsid>
                        <goals>
                            <goal>generategoal>
                        goals>
                    execution>
                executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generatorgroupId>
                        <artifactId>mybatis-generator-coreartifactId>
                        <version>1.3.2version>
                    dependency>
                dependencies>
            plugin>

generator.xml一般放在resources目录下(注意修改自己实际的jar包位置和数据库连接信息以及表的名称)。


DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    
    <classPathEntry
            location="E:\ProgramFile\apache-maven-3.8.3\rep\mysql\mysql-connector-java\8.0.27\mysql-connector-java-8.0.27.jar"/>
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            
            <property name="suppressAllComments" value="true"/>
        commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/xinpai_food?serverTimezone=UTC"
                        userId="root"
                        password="123456">
        jdbcConnection>
        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        <javaModelGenerator targetPackage="com.unicome.domain"
                            targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
            
            <property name="trimStrings" value="true"/>
        javaModelGenerator>
        
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="src/main/resources">
            
            <property name="enableSubPackages" value="false"/>
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.unicome.mapper"
                             targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
        javaClientGenerator>
        
        <table tableName="po_in_out"
               enableCountByExample="true"
               enableUpdateByExample="true"
               enableDeleteByExample="true"
               enableSelectByExample="true"
               selectByExampleQueryId="true">
        table>
        <table tableName="pur_plan"
               enableCountByExample="true"
               enableUpdateByExample="true"
               enableDeleteByExample="true"
               enableSelectByExample="true"
               selectByExampleQueryId="true">
        table>
        <table tableName="tol_in_out"
               enableCountByExample="true"
               enableUpdateByExample="true"
               enableDeleteByExample="true"
               enableSelectByExample="true"
               selectByExampleQueryId="true">
        table>
    context>
generatorConfiguration>

双击运行逆行工程。

从零创建微服务(一)_第6张图片

4.application.yaml

server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/cloud-user?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.bzw.domain  #注意修改成自己的持久化类路径
  mapper-locations: classpath:mapper/*Mapper.xml
  configuration:
    map-underscore-to-camel-case: true
logging:
  level:
    cn.itcast: debug
  pattern:
    dateformat: MM-dd HH:mm:ss:SSS

5.service层

​ 接口:

package com.bzw.service;

import com.bzw.domain.TbUser;

public interface UserService {

    TbUser findUserById(Long id);
}

​ 实现类:

package com.bzw.service.impl;

import com.bzw.domain.TbUser;
import com.bzw.mapper.TbUserMapper;
import com.bzw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public TbUser findUserById(Long id) {
        return tbUserMapper.selectByPrimaryKey(id);
    }
}

6.controller层

package com.bzw.controller;

import com.bzw.domain.TbUser;
import com.bzw.service.UserService;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("{userId}")
    public TbUser findUserById(@PathVariable("userId") Long id){
        return userService.findUserById(id);
    }
}

启动类:

package com.bzw;

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

@SpringBootApplication
public class UserServiceApplication {

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

}

7.再新建一个module(order-service)。步骤和user-service是一样的(注意修改端口号)。我们想在查询订单信息的同时也把用户信息也一起查出来,在持久化类中加一个User类。

package com.bzw.domain;

public class User {

    private Long id;

    private String username;

    private String address;

    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 == null ? null : username.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }


}

8.注入RestTemplate,远程调用。

​ 在order-service启动类中添加如下代码:

 /**
     *
     * 创建RestTemplate,并注入Spring(远程调用)
     */
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

9.注意service层写法。

package com.bzw.service.impl;

import com.bzw.domain.TbOrder;
import com.bzw.domain.User;
import com.bzw.mapper.TbOrderMapper;
import com.bzw.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public TbOrder findOrderById(Long id) {
        TbOrder tbOrder = new TbOrder();
        tbOrder = tbOrderMapper.selectByPrimaryKey(id);
        User user = new User();
        String url = "http://localhost:8081/user/" + tbOrder.getUserId();
        user = restTemplate.getForObject(url,User.class);
        tbOrder.setUser(user);
        return tbOrder;
    }
}

10.结果。

从零创建微服务(一)_第7张图片

成功。

11.存在问题。

​ 在order-service的service层可以看到我们采用硬编码的方式,把url写死了。这样肯定是不行的。那么该如何解决,下一篇将会介绍。

你可能感兴趣的:(微服务,微服务)