傻瓜式搭建spring-cloud之service

service是spring-cloud中的微服務節點,具體實現了模塊的業務(用戶中心、工作流中心、某業務模塊等等),同樣支持負載。

增加依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.1.9</version>
        </dependency>

增加了web、mybatis-plus、druid的支持,基本的業務模塊這幾個應該是需要的,后續再補充定時任務、MQ、redis等

yml配置
# 公共配置
eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8010/eureka/ #eureka服務注冊地址

mybatis-plus:
    mapper-locations: classpath:/com/eqlian/*/mapper/*Mapper.xml
    #實體掃描,多個package用逗號或者分號分隔
    typeAliasesPackage: com.**.entity
    global-config:
        #主鍵類型  0:"數據庫ID自增", 1:"用戶輸入ID",2:"全局唯一ID (數字類型唯一ID)", 3:"全局唯一ID UUID";
        id-type: 3
        #字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
        field-strategy: 2
        #駝峰下劃線轉換
        db-column-underline: true
        #刷新mapper 調試神器
        refresh-mapper: true
    configuration:
        map-underscore-to-camel-case: true
        cache-enabled: false
spring:
    datasource:
        name: test
        url: jdbc:mysql://192.168.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
        username: root
        password: root
        # 使用druid數據源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
    application:
        name: service-system
server:
    port: 8911
啟動類
@ComponentScan("com.**.controller")
@ComponentScan("com.**.service")
@EnableEurekaClient
@SpringBootApplication
public class SmApplication {
    public static void main(String[] args) {
        SpringApplication.run(SmApplication.class, args);
    }
}
config
@Configuration
@MapperScan("com.eqlian.**.mapper")
public class MybatisPlusConfig {
    /*
     * 分頁插件,自動識別數據庫類型
     * 多租戶,請參考官網【插件擴展】
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
@Component
public class SpringContextAware implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextAware.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static <T> T getBean(String name){
        return (T) applicationContext.getBean(name);
    }

}
controller
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User get(@PathVariable("id") String id) {
        return  userService.getById(id);
    }
}
service
@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public User getById(String id) {
        return  selectById(id);
    }
}
mapper
public interface UserMapper extends BaseMapper<User> {
    // 這里可寫其他復雜查詢,簡單的增刪改查用serviceimpl提供的接口即可滿足
}
entity
@TableName("t_user")
@Data
public class User extends Model<User> {

    @TableId(value = "pk_user", type = IdType.UUID)
    private String pkUser;
    /**
     * 姓名
     */
    private String name;
    /**
     * 密碼
     */
    private String password;
    /**
     * 用戶名、登錄名
     */
    private String username;
    /**
     * 狀態:0=啟用,1=禁用
     */
    private Integer status;

    @Override
    protected Serializable pkVal() {
        return getPkUser();
    }

}

基本的查詢就寫完了,啟動服務自動連接到注冊中心。

這里接口的地址是 http://localhost:8911/user/{id} 但我們肯定不會把這個地址暴露出去

zuul網關這時會把這個接口代理出去,所以前端無需關心微服務真正的ip地址,只需要請求zuul代理的路徑即可。

再講一下zuul代理的規則

zuul:
  routes:
    sm:
      path: /demo/system/**
      serviceId: service-system

可以看到zuul里配置路由規則是將所有/demo/system/**的請求路由到service-system這個微服務上,而service-system則是咱們在yml中設置的微服務id。

至此一個最簡單的查詢模塊就開發和發布完成了。

PS: 如何負載均衡?
很簡答,你這個微服務模塊啟動2個進程注冊到注冊中心就會自動負載了,serviceid相同但ip:port不同。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容