栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第五阶段项目公共基础部分

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第五阶段项目公共基础部分

此基部分共包含四个module:common、item-service、user-service、order-service,调用关系如下
各自的访问端口分配如下

1.common项目 1.1 创建父项目

IDEA -> New -> Project… -> Spring Initializar ->[start.spring.io,name:springcloud1,Group:cn.tedu] ,修改pom.xml文件,这个项目会做为版本管理的公共项目被其他的子项目引用,所以这里配置了springboot和springcloud的版本,并添加了test的依赖以及spring-boot-maven-plugin插件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.2.RELEASE
         
    
    cn.tedu
    springcloud1
    0.0.1-SNAPSHOT
    springcloud1
    pom
    Demo project for Spring Boot
    
        1.8
        Hoxton.SR12
    
    
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                
                pom
                import
            
        
    

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

删掉父项目的src目录就可以了,这里用不到

1.2 创建module:common

在父项目的名字上右键-New -> module,这里不需要继承父项目,所以Parent后面改成None选项

修改pom.xml文件



    4.0.0

    cn.tedu
    sp01-commons
    1.0-SNAPSHOT

    
        8
        8
    
    
        
        
            com.fasterxml.jackson.module
            jackson-module-parameter-names
            2.9.8
        
        
            com.fasterxml.jackson.datatype
            jackson-datatype-jdk8
            2.9.8
        
        
            com.fasterxml.jackson.datatype
            jackson-datatype-jsr310
            2.9.8
        
        
            com.fasterxml.jackson.datatype
            jackson-datatype-guava
            2.9.8
        
        
        
            javax.servlet
            javax.servlet-api
            3.1.0
        
        
        
            org.projectlombok
            lombok
            1.18.6
        
        
        
            org.slf4j
            slf4j-api
            1.7.26
        
        
            org.apache.commons
            commons-lang3
            3.9
        

    

1.2.1 创建pojo.Item
package pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Item {

    private Integer id;
    private String name;
    private Integer count;
}
1.2.2 创建pojo.User
package pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}
1.2.3 创建pojo.Order
package pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Order {

    private String id;
    private User user;
    private List items;
}
1.2.4 创建service.ItemService接口
package service;

import pojo.Item;

import java.util.List;

public interface ItemService {
    // 根据订单号查询订单下的商品列表
    public List getItems(String orderId);
    
    //根据给定的商品列表,减少对应商品的库存
    void decreaseNumbers(List list);
}
1.2.5 创建service.UserService接口
package service;

import pojo.User;

public interface UserService {
    // 根据用户id查询用户
    User getUser(Integer userId);

    // 向指定用户增加积分
    void addScore(Integer userId, Integer score);
}
1.2.6 创建service.OrderService接口
package service;

import pojo.Order;

public interface OrderService {
    // 根据orderId查询对应订单
    Order getOrder(String orderId);

    // 增加订单
    void addOrder(Order order);
}
1.2.7 创建web.util.cookieUtil类
package web.util;


import javax.servlet.http.cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class cookieUtil {

    
    public static void setcookie(HttpServletResponse response,
                                 String name, String value, String domain, String path, int maxAge) {
        cookie cookie = new cookie(name, value);
        if(domain != null) {
            cookie.setDomain(domain);
        }
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        response.addcookie(cookie);
    }
    public static void setcookie(HttpServletResponse response, String name, String value, int maxAge) {
        setcookie(response, name, value, null, "/", maxAge);
    }
    public static void setcookie(HttpServletResponse response, String name, String value) {
        setcookie(response, name, value, null, "/", 3600);
    }
    public static void setcookie(HttpServletResponse response, String name) {
        setcookie(response, name, "", null, "/", 3600);
    }

    
    public static String getcookie(HttpServletRequest request, String name) {
        String value = null;
        cookie[] cookies = request.getcookies();
        if (null != cookies) {
            for (cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                }
            }
        }
        return value;
    }

    
    public static void removecookie(HttpServletResponse response, String name, String domain, String path) {
        setcookie(response, name, "", domain, path, 0);
    }
}
1.2.8 创建web.util.cookieUtil类
package web.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtil {
    private static ObjectMapper mapper;
    private static JsonInclude.Include DEFAULT_PROPERTY_INCLUSION = JsonInclude.Include.NON_DEFAULT;
    private static boolean IS_ENABLE_INDENT_OUTPUT = false;
    private static String CSV_DEFAULT_COLUMN_SEPARATOR = ",";
    static {
        try {
            initMapper();
            configPropertyInclusion();
            configIndentOutput();
            configCommon();
        } catch (Exception e) {
            log.error("jackson config error", e);
        }
    }

    private static void initMapper() {
        mapper = new ObjectMapper();
    }

    private static void configCommon() {
        config(mapper);
    }

    private static void configPropertyInclusion() {
        mapper.setSerializationInclusion(DEFAULT_PROPERTY_INCLUSION);
    }

    private static void configIndentOutput() {
        mapper.configure(SerializationFeature.INDENT_OUTPUT, IS_ENABLE_INDENT_OUTPUT);
    }

    private static void config(ObjectMapper objectMapper) {
        objectMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        objectMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
        objectMapper.enable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
        objectMapper.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
        objectMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
        objectMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        objectMapper.registerModule(new ParameterNamesModule());
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(new GuavaModule());
    }
    public static void setSerializationInclusion(JsonInclude.Include inclusion) {
        DEFAULT_PROPERTY_INCLUSION = inclusion;
        configPropertyInclusion();
    }

    public static void setIndentOutput(boolean isEnable) {
        IS_ENABLE_INDENT_OUTPUT = isEnable;
        configIndentOutput();
    }

    public static  V from(URL url, Class c) {
        try {
            return mapper.readValue(url, c);
        } catch (IOException e) {
            log.error("jackson from error, url: {}, type: {}", url.getPath(), c, e);
            return null;
        }
    }

    public static  V from(InputStream inputStream, Class c) {
        try {
            return mapper.readValue(inputStream, c);
        } catch (IOException e) {
            log.error("jackson from error, type: {}", c, e);
            return null;
        }
    }

    public static  V from(File file, Class c) {
        try {
            return mapper.readValue(file, c);
        } catch (IOException e) {
            log.error("jackson from error, file path: {}, type: {}", file.getPath(), c, e);
            return null;
        }
    }

    public static  V from(Object jsonObj, Class c) {
        try {
            return mapper.readValue(jsonObj.toString(), c);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", jsonObj.toString(), c, e);
            return null;
        }
    }

    public static  V from(String json, Class c) {
        try {
            return mapper.readValue(json, c);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", json, c, e);
            return null;
        }
    }

    public static  V from(URL url, TypeReference type) {
        try {
            return mapper.readValue(url, type);
        } catch (IOException e) {
            log.error("jackson from error, url: {}, type: {}", url.getPath(), type, e);
            return null;
        }
    }

    public static  V from(InputStream inputStream, TypeReference type) {
        try {
            return mapper.readValue(inputStream, type);
        } catch (IOException e) {
            log.error("jackson from error, type: {}", type, e);
            return null;
        }
    }

    public static  V from(File file, TypeReference type) {
        try {
            return mapper.readValue(file, type);
        } catch (IOException e) {
            log.error("jackson from error, file path: {}, type: {}", file.getPath(), type, e);
            return null;
        }
    }

    public static  V from(Object jsonObj, TypeReference type) {
        try {
            return mapper.readValue(jsonObj.toString(), type);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", jsonObj.toString(), type, e);
            return null;
        }
    }

    public static  V from(String json, TypeReference type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", json, type, e);
            return null;
        }
    }

    public static  String to(List list) {
        try {
            return mapper.writevalueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("jackson to error, obj: {}", list, e);
            return null;
        }
    }

    public static  String to(V v) {
        try {
            return mapper.writevalueAsString(v);
        } catch (JsonProcessingException e) {
            log.error("jackson to error, obj: {}", v, e);
            return null;
        }
    }

    public static  void toFile(String path, List list) {
        try (Writer writer = new FileWriter(new File(path), true)) {
            mapper.writer().writevalues(writer).writeAll(list);
            writer.flush();
        } catch (Exception e) {
            log.error("jackson to file error, path: {}, list: {}", path, list, e);
        }
    }

    public static  void toFile(String path, V v) {
        try (Writer writer = new FileWriter(new File(path), true)) {
            mapper.writer().writevalues(writer).write(v);
            writer.flush();
        } catch (Exception e) {
            log.error("jackson to file error, path: {}, obj: {}", path, v, e);
        }
    }

    public static String getString(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).toString();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get string error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static Integer getInt(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).intValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get int error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static Long getLong(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).longValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get long error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static Double getDouble(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).doublevalue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get double error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static BigInteger getBigInteger(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return new BigInteger(String.valueOf(0.00));
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).bigIntegerValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get biginteger error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static BigDecimal getBigDecimal(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).decimalValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get bigdecimal error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static boolean getBoolean(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return false;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).booleanValue();
            } else {
                return false;
            }
        } catch (IOException e) {
            log.error("jackson get boolean error, json: {}, key: {}", json, key, e);
            return false;
        }
    }

    public static byte[] getByte(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).binaryValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get byte error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static  ArrayList getList(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        String string = getString(json, key);
        return from(string, new TypeReference>() {});
    }

    public static  String add(String json, String key, T value) {
        try {
            JsonNode node = mapper.readTree(json);
            add(node, key, value);
            return node.toString();
        } catch (IOException e) {
            log.error("jackson add error, json: {}, key: {}, value: {}", json, key, value, e);
            return json;
        }
    }

    private static  void add(JsonNode jsonNode, String key, T value) {
        if (value instanceof String) {
            ((ObjectNode) jsonNode).put(key, (String) value);
        } else if (value instanceof Short) {
            ((ObjectNode) jsonNode).put(key, (Short) value);
        } else if (value instanceof Integer) {
            ((ObjectNode) jsonNode).put(key, (Integer) value);
        } else if (value instanceof Long) {
            ((ObjectNode) jsonNode).put(key, (Long) value);
        } else if (value instanceof Float) {
            ((ObjectNode) jsonNode).put(key, (Float) value);
        } else if (value instanceof Double) {
            ((ObjectNode) jsonNode).put(key, (Double) value);
        } else if (value instanceof BigDecimal) {
            ((ObjectNode) jsonNode).put(key, (BigDecimal) value);
        } else if (value instanceof BigInteger) {
            ((ObjectNode) jsonNode).put(key, (BigInteger) value);
        } else if (value instanceof Boolean) {
            ((ObjectNode) jsonNode).put(key, (Boolean) value);
        } else if (value instanceof byte[]) {
            ((ObjectNode) jsonNode).put(key, (byte[]) value);
        } else {
            ((ObjectNode) jsonNode).put(key, to(value));
        }
    }

    public static String remove(String json, String key) {
        try {
            JsonNode node = mapper.readTree(json);
            ((ObjectNode) node).remove(key);
            return node.toString();
        } catch (IOException e) {
            log.error("jackson remove error, json: {}, key: {}", json, key, e);
            return json;
        }
    }

    public static  String update(String json, String key, T value) {
        try {
            JsonNode node = mapper.readTree(json);
            ((ObjectNode) node).remove(key);
            add(node, key, value);
            return node.toString();
        } catch (IOException e) {
            log.error("jackson update error, json: {}, key: {}, value: {}", json, key, value, e);
            return json;
        }
    }

    public static String format(String json) {
        try {
            JsonNode node = mapper.readTree(json);
            return mapper.writerWithDefaultPrettyPrinter().writevalueAsString(node);
        } catch (IOException e) {
            log.error("jackson format json error, json: {}", json, e);
            return json;
        }
    }

    public static boolean isJson(String json) {
        try {
            mapper.readTree(json);
            return true;
        } catch (Exception e) {
            log.error("jackson check json error, json: {}", json, e);
            return false;
        }
    }

    private static InputStream getResourceStream(String name) {
        return JsonUtil.class.getClassLoader().getResourceAsStream(name);
    }

    private static InputStreamReader getResourceReader(InputStream inputStream) {
        if (null == inputStream) {
            return null;
        }
        return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    }
}
1.2.9 创建web.util.cookieUtil类
package web.util;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class JsonResult {
    
    public static final int SUCCESS = 200;

    
    public static final int NOT_LOGIN = 400;

    
    public static final int EXCEPTION = 401;

    
    public static final int SYS_ERROR = 402;

    
    public static final int PARAMS_ERROR = 403;

    
    public static final int NOT_SUPPORTED = 410;

    
    public static final int INVALID_AUTHCODE = 444;

    
    public static final int TOO_FREQUENT = 445;

    
    public static final int UNKNOWN_ERROR = 499;

    private int code;
    private String msg;
    private T data;



    public static JsonResult build() {
        return new JsonResult();
    }
    public static JsonResult build(int code) {
        return new JsonResult().code(code);
    }
    public static JsonResult build(int code, String msg) {
        return new JsonResult().code(code).msg(msg);
    }
    public static  JsonResult build(int code, T data) {
        return new JsonResult().code(code).data(data);
    }
    public static  JsonResult build(int code, String msg, T data) {
        return new JsonResult().code(code).msg(msg).data(data);
    }

    public JsonResult code(int code) {
        this.code = code;
        return this;
    }
    public JsonResult msg(String msg) {
        this.msg = msg;
        return this;
    }
    public JsonResult data(T data) {
        this.data = data;
        return this;
    }


    public static JsonResult ok() {
        return build(SUCCESS);
    }
    public static JsonResult ok(String msg) {
        return build(SUCCESS, msg);
    }
    public static  JsonResult ok(T data) {
        return build(SUCCESS, data);
    }
    public static JsonResult err() {
        return build(EXCEPTION);
    }
    public static JsonResult err(String msg) {
        return build(EXCEPTION, msg);
    }

    @Override
    public String toString() {
        return JsonUtil.to(this);
    }
}

至此,sp01-commons这个module就写好了

1.3 创建sp02-itemservice


这里的pom.xml需要把springcloud1做为parent,并在dependencies里面引入sp01



    
        springcloud1
        cn.tedu
        0.0.1-SNAPSHOT
    
    4.0.0

    sp02-itemservice
    0.0.1-SNAPSHOT
    sp02-itemservice
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            cn.tedu
            sp01-commons
            1.0-SNAPSHOT
        
    

把resource目录下的application.properties文件改成application.yml

spring:
  application:
    name: item-service
server:
  port: 8001
1.3.1 创建service.ItemServiceImpl类
package cn.tedu.sp02.service;

import lombok.extern.slf4j.Slf4j;
import pojo.Item;
import service.ItemService;

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

@Slf4j
@Service
public class ItemServiceImpl implements ItemService {

    @Override
    public List getItems(String orderId) {
        // 模拟查询到了商品的列表
        List items = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            items.add(new Item(i, "商品" + i, i));
        }
        return items;
    }

    @Override
    public void decreaseNumbers(List list) {
        // 模拟减少库存
        for (Item item : list) {
            log.info("商品:{} 减少了 {} 件库存",item.getName(),item.getCount());
        }
    }
}
1.3.2 创建controller.ItemController类
package cn.tedu.sp02.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import pojo.Item;
import service.ItemService;
import web.util.JsonResult;

import java.util.List;

@Slf4j
@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Value("${server.port:8001}")
    private Integer serverPort;

    @GetMapping("/{orderId}")
    public JsonResult> getItems(@PathVariable("orderId") String orderId) {
        log.info("server.port:{}  orderId:{}",serverPort,orderId);
        return JsonResult.ok(itemService.getItems(orderId));
    }

    @PostMapping("/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List items) {
        itemService.decreaseNumbers(items);
        return JsonResult.ok();
    }
}
1.3.3 测试

在父项目上右键=>New=>HTTP Request,创建一个请求测试文件

############################
# item-service
############################
# 根据订单号获得对应商品列表
GET http://localhost:8001/1

###
# 减少指定商品列表中所有商品的库存
POST http://localhost:8001/decreaseNumber
Content-Type: application/json

[
  {
    "id": 0,
    "name": "商品0",
    "count": 0
  },
  {
    "id": 1,
    "name": "商品1",
    "count": 1
  },
  {
    "id": 2,
    "name": "商品2",
    "count": 2
  },
  {
    "id": 3,
    "name": "商品3",
    "count": 3
  },
  {
    "id": 4,
    "name": "商品4",
    "count": 4
  },
  {
    "id": 5,
    "name": "商品5",
    "count": 5
  },
  {
    "id": 6,
    "name": "商品6",
    "count": 6
  },
  {
    "id": 7,
    "name": "商品7",
    "count": 7
  },
  {
    "id": 8,
    "name": "商品8",
    "count": 8
  },
  {
    "id": 9,
    "name": "商品9",
    "count": 9
  }
]
1.4 创建sp03-userservice


修改pom.xml文件



    
        springcloud1
        cn.tedu
        0.0.1-SNAPSHOT
    
    4.0.0

    sp03-userservice
    0.0.1-SNAPSHOT
    sp03-userservice
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            cn.tedu
            sp01-commons
            1.0-SNAPSHOT
        
    

配置application.yml文件

server:
  port: 8101
spring:
  application:
    name: user-service
sp:
  user-service:
    users: "[{"id":7, "username":"abc","password":"123"},{"id":8, "username":"def","password":"456"},{"id":9, "username":"ghi","password":"789"}]"
1.4.1 创建service.UserServiceImpl
package cn.tedu.sp03.service;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pojo.User;
import service.UserService;
import web.util.JsonUtil;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    //读取application.yml中的配置
    @Value("${sp.user-service.users}")
    private String userJsonString;


    @Override
    public User getUser(Integer userId) {
        log.info("userJson:{}", userJsonString);

        // 模拟数据库里面的数据
        // 使用jackson反序列化对象列表的用法
        // 详细知识可以看jackson的序列化与反序列化
        List list = JsonUtil.from(userJsonString, new TypeReference>() {
        });

        // 模拟查询指定id的user
        for (User user : list) {
            if (user.getId() != null && user.getId().equals(userId)) {
                return user;
            }
        }
        return new User(userId, "新用户" + userId, "新用户的密码:" + userId);
    }

    @Override
    public void addScore(Integer userId, Integer score) {
        log.info("用户:{} 增加了 {} 积分", userId, score);
    }
}
1.4.2 创建controller.UserController
package cn.tedu.sp03.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pojo.User;
import service.UserService;
import web.util.JsonResult;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{userId}")
    public JsonResult getUser(@PathVariable("userId") Integer userId) {
        log.info("获取用户:{}", userId);
        User user = userService.getUser(userId);
        return JsonResult.ok(user);
    }

    @PostMapping("/{userId}/score")
    public JsonResult addScore(@PathVariable("userId") Integer userId, @RequestParam("score") Integer score) {
        userService.addScore(userId, score);
        return JsonResult.ok();
    }
}
1.4.3 请求测试

启动项目,在1.3.3创建的请求文件中添加如下代码并测试

############################
# user-service
############################
# 根据用户id查询用户
GET http://localhost:8101/8

#得到如下结果
#{
#  "code": 200,
#  "msg": null,
#  "data": {
#    "id": 8,
#    "username": "def",
#    "password": "456"
#  }
#}

###
# 给指定用户增加积分
POST http://localhost:8101/7/score?score=10

# 后台打印如下内容:
# 用户:7 增加了 10 积分
1.5 创建sp04-orderservice


配置pom.xml文件



    
        springcloud1
        cn.tedu
        0.0.1-SNAPSHOT
    
    4.0.0

    sp04-orderservice
    0.0.1-SNAPSHOT
    sp04-orderservice
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            cn.tedu
            sp01-commons
            1.0-SNAPSHOT
        
    

配置appcliation.yml文件

spring:
  application:
    name: order-service
server:
  port: 8201
1.5.1创建service.OrderServiceImpl
package cn.tedu.sp04.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pojo.Order;
import service.OrderService;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Override
    public Order getOrder(String orderId) {
        // 由于还没有注册中心,所以暂时没法使用feign
        //TODO: 调用user-service获取用户信息
        //TODO: 调用item-service获取商品信息
        Order order = new Order();
        order.setId(orderId);
        return order;
    }

    @Override
    public void addOrder(Order order) {
        // 由于还没有注册中心,所以暂时没法使用feign
        //TODO: 调用item-service减少商品库存
        //TODO: 调用user-service增加用户积分
        log.info("保存订单:{}", order);
    }
}

1.5.2 创建controller.OrderController
package cn.tedu.sp04.controller;

import lombok.extern.slf4j.Slf4j;
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.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import pojo.Item;
import pojo.Order;
import pojo.User;
import service.OrderService;
import web.util.JsonResult;

import java.util.Arrays;

@Slf4j
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/{orderId}")
    public JsonResult getOrder(@PathVariable("orderId") String orderId) {
        log.info("获取订单,订单号:{}", orderId);
        Order order = orderService.getOrder(orderId);
        return JsonResult.ok(order);
    }

    @PostMapping("/")
    public JsonResult addOrder() {
        // 模拟添加订单
        Order order = new Order();
        order.setId("123");
        order.setUser(new User(1, "新订单用户", "123321"));
        order.setItems(Arrays.asList(new Item[]{
                new Item(1, "手机", 1),
                new Item(2, "电脑", 2),
                new Item(3, "显示器", 3),
                new Item(4, "投影仪", 4),
                new Item(5, "音箱", 5),
        }));
        orderService.addOrder(order);
        return JsonResult.ok();
    }
}
1.5.3 测试请求

添加如下请求代码

############################
# order-service
############################
# 根据id查询订单
GET http://localhost:8201/1

# 返回如下结果
#{
#  "code": 200,
#  "msg": null,
#  "data": {
#    "id": "1",
#    "user": null,
#    "items": null
#  }
#}

###
# 添加订单
POST http://localhost:8201/

# 控制台会打印
# 保存订单:Order(id=123, user=User(id=1, username=新订单用户, password=123321), items=[Item(id=1, name=手机, count=1), Item(id=2, name=电脑, count=2), Item(id=3, name=显示器, count=3), Item(id=4, name=投影仪, count=4), Item(id=5, name=音箱, count=5)])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/710902.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号