@[toc]

Enable or disable code-push-server

  • To start the code-push-server server: CD to the code-push-server directory, run the./bin/ WWW command to start the server, or click on the file directly (if you want to start MySQL server).
  • To shut down the code-push-server server, close the terminal of the server

Install the MySQL server

Code-push-server uses the mysql database and requires this environment to be installed

1.1 Downloading and Installing mysql

Mysql website

1.2 Configuring Global Commands

1) CD/usr/local/bin /

2) sudo ln – fs/usr/local/mysql/bin/mysql mysql mysql version 3), is there a version information

1.3 Initializing the mysql Database

Create table initialization, run in code-push-server directory: 1234567890 is your mysql database password.

/bin/db init --dbhost 127.0.0.1 --dbuser root --dbpassword 1234567890Copy the code

Client does not support authentication protocol requested by server; consider upgrading MySQL client

(1) Add two lines at the end of.bash_profile

alias mysql=/usr/local/mysql/bin/mysql
alias mysqladmin=/usr/local/mysql/bin/mysqladmin
Copy the code

(2) Run mysql -u root -p and enter your database password

(3) run these three lines separately :(1234567890 is your mysql password)

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '1234567890' ALTER USER 'root'@'localhost' IDENTIFIED WITH  mysql_native_password BY '1234567890' SELECT plugin FROM mysql.user WHERE User = 'root'Copy the code

Second, the construction of code-push-server

2.1. Install and start code-push-server

$ git clone https://github.com/lisong/code-push-server.git
$ cd code-push-server
$ npm install
Copy the code

2.2. Config. Js configuration Modification Problem

Open the configuration file ~/code-push-server/config/config.js, modify the three places, and create a new directory

B. Change the downloadUrl in Local to the local IP address. C. Change the storageType in common to local. D, to www.grc.com/passwords.h… E, downloadUrl: I used “127.0.0.1”, and then I need to replace “127.0.0.1” with an external address for the Internet. F, install the directory structure in the configuration file and create storage and data folders. Such as “/ Users/zhanglei/workspace/storage”, “/ Users/zhanglei/workspace/data”, the former is used for database related data path record, which is used for image resources such as files and jsbundle

2.3. Modify the docker/config. Js

Change username and password to mysql database account; Use “127.0.0.1” for host; Port The default value is 3306

2.4, start the code-push-server server

CD go to the code-push-server directory and run the following command

/bin/ WWW # Open http://127.0.0.1:3000 (you can also use the local IP address to access http://192.168.0.7:3000), the default login password admin/123456, to this server side to complete the configuration. Then post all the JS files

var os = require('os');

var config = {};
config.development = {
  // Config for database, only support mysql.
  db: {
    username: process.env.RDS_USERNAME || "root".password: process.env.RDS_PASSWORD || '123456'.database: process.env.DATA_BASE || "codepush".host: process.env.RDS_HOST || "127.0.0.1".port: process.env.RDS_PORT || 3306.dialect: "mysql".logging: false.operatorsAliases: false,},// Config for qiniu (http://www.qiniu.com/) cloud storage when storageType value is "qiniu".
  qiniu: {
    accessKey: "".secretKey: "".bucketName: "".downloadUrl: "" // Binary files download host address.
  },
  // Config for upyun (https://www.upyun.com/) storage when storageType value is "upyun"
  upyun: {
    storageDir: process.env.UPYUN_STORAGE_DIR,
    serviceName: process.env.UPYUN_SERVICE_NAME,
    operatorName: process.env.UPYUN_OPERATOR_NAME,
    operatorPass: process.env.UPYUN_OPERATOR_PASS,
    downloadUrl: process.env.DOWNLOAD_URL,
  },
  // Config for Amazon s3 (https://aws.amazon.com/cn/s3/) storage when storageType value is "s3".
  s3: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    sessionToken: process.env.AWS_SESSION_TOKEN, //(optional)
    bucketName: process.env.BUCKET_NAME,
    region: process.env.REGION,
    downloadUrl: process.env.DOWNLOAD_URL, // binary files download host address.
  },
  // Config for Aliyun OSS (https://www.aliyun.com/product/oss) when storageType value is "oss".
  oss: {
    accessKeyId: "".secretAccessKey: "".endpoint: "".bucketName: "".prefix: "".// Key prefix in object key
    downloadUrl: "".// binary files download host address.
  },
  // Config for tencentyun COS (https://cloud.tencent.com/product/cos) when storageType value is "oss".
  tencentcloud: {
    accessKeyId: "".secretAccessKey: "".bucketName: "".region: "".downloadUrl: "".// binary files download host address.
  },
  // Config for local storage when storageType value is "local".
  local: {
    // Binary files storage dir, Do not use tmpdir and it's public download dir.
    storageDir: "/Users/zhanglei/workspace/storage".// Binary files download host address which Code Push Server listen to. the files storage in storageDir.
    downloadUrl: "http://127.0.0.1:3000/download".// public static download spacename.
    public: '/download'
  },
  jwt: {
    // Recommended: 63 random alpha-numeric characters
    // Generate using: https://www.grc.com/passwords.htm
    tokenSecret: 't1iwqorl8flWwGzDc2bgveqyUIjJt3GyJOZrosEDPbvEl76rvplHQpAzfzUmoeV'
  },
  common: {
    /* * tryLoginTimes is control login error times to avoid force attack. * if value is 0, no limit for login auth, it may not safe for account. when it's a number, it means you can * try that times today. but it need config redis server. */
    tryLoginTimes: 0.// CodePush Web(https://github.com/lisong/code-push-web) login address.
    / / codePushWebUrl: "http://127.0.0.1:3001/login".
    // create patch updates's number. default value is 3
    diffNums: 3.// data dir for caclulate diff files. it's optimization.
    dataDir: "/Users/zhanglei/workspace/data".// storageType which is your binary package files store. options value is ("local" | "qiniu" | "s3"| "oss" || "tencentcloud")
    storageType: process.env.STORAGE_TYPE || "local".// options value is (true | false), when it's true, it will cache updateCheck results in redis.
    updateCheckCache: false.// options value is (true | false), when it's true, it will cache rollout results in redis
    rolloutClientUniqueIdCache: false,},// Config for SMTP email, register module need validate user email project source https://github.com/nodemailer/nodemailer
  smtpConfig: {host: "smtp.aliyun.com".port: 465.secure: true.auth: {
      user: "".pass: ""}},// Config for redis (register module, tryLoginTimes module)
  redis: {
    default: {
      host: "127.0.0.1".port: 6379.retry_strategy: function (options) {
        if (options.error.code === 'ECONNREFUSED') {
          // End reconnecting on a specific error and flush all commands with a individual error
          return new Error('The server refused the connection');
        }
        if (options.total_retry_time > 1000 * 60 * 60) {
            // End reconnecting after a specific timeout and flush all commands with a individual error
            return new Error('Retry time exhausted');
        }
        if (options.times_connected > 10) {
            // End reconnecting with built in error
            return undefined;
        }
        // reconnect after
        return Math.max(options.attempt * 100.3000);
      }
    }
  }
}

config.development.log4js = {
  appenders: {console: { type: 'console'}},
  categories : {
    "default": { appenders: ['console'].level:'error'},
    "startup": { appenders: ['console'].level:'info'},
    "http": { appenders: ['console'].level:'info'}
  }
}

config.production = Object.assign({}, config.development);
module.exports = config;

Copy the code

3. Client configuration process

3.1 Create a React-native hot update test project

Create a react-native init with a specified version number. React-native init demo --version 0.53.3 Verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose verbose Therefore, the recommended full command is: react-native init demo --verbose --version 0.53.3Copy the code

3.2 APP Changing the REMOTE Server ADDRESS

package com.hongshi.rn;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.hongshi.BuildConfig;
import com.hongshi.rn.bridge.NativeBridgePackage;
import com.microsoft.codepush.react.CodePush;
import com.reactnativecommunity.webview.RNCWebViewPackage;
import com.reactnativecommunity.asyncstorage.AsyncStoragePackage;
import com.airbnb.android.react.lottie.LottiePackage;
import com.react.rnspinkit.RNSpinkitPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

    @Override
    protected String getJSBundleFile(a){
      return CodePush.getJSBundleFile();
    }

    @Override
    public boolean getUseDeveloperSupport(a) {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages(a) {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new RNCWebViewPackage(),
            new AsyncStoragePackage(),
            new LottiePackage(),
            new RNSpinkitPackage(),
            new RNGestureHandlerPackage(),
              // CodePush(String deploymentKey, Context context, boolean isDebugMode, @NonNull String serverUrl)
              new CodePush(null, getApplicationContext(), BuildConfig.DEBUG, "http://127.0.0.1:3000"),
              new NativeBridgePackage()
      );
    }

    @Override
    protected String getJSMainModuleName(a) {
      return "index"; }};@Override
  public ReactNativeHost getReactNativeHost(a) {
    return mReactNativeHost;
  }

  @Override
  public void onCreate(a) {
    super.onCreate();
    SoLoader.init(this./* native exopackage */ false); }}Copy the code

3.3 Registering a code-push account

During the registration process, the authorization webpage will be opened, and the token of the project will be used to open http://127.0.0.1:3000(. The password of my code-push-server account is account: admin password: 123456), get the token and put it in code-push

$ code-push register
Copy the code
  • Register the App on the code-push server
Add the deployment environment code-push deployment add <app_name> test// Create the test environment add the application platform code-push app add <app_name> < OS > <platform> For example, add the iOS platform $code-push app add iOSRNHybrid ios React-native, multiple platforms Perform multiple operations to view the app list code-push app list View the app environment information code-push deployment list  <app_name> --format jsonCopy the code

Such as

Code-push relea-react DigitalMineApp -ios iOS -m true -d Staging --des "optimizationcontinuously click" -t "2.4.0" code-push relea-react Digitalmineapp-android Android -m true -d Staging --des "optimize continuously click" -t "2.4.0" code-push promote DigitalMineapp-Android Staging ProductionCopy the code

3.4 ReactNative project integrates code-push

NPM install react-native code-push --save add dependency NPM link react-native code-pushCopy the code

· React-native app.js integration code

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';
import CodePush from "react-native-code-push"; / / introduce code - a push

let codePushOptions = {
  // Set the frequency of checking for updates
  // when the ON_APP_RESUME APP returns to the foreground
  //ON_APP_START when the APP is started
  //MANUAL MANUAL check
  checkFrequency : CodePush.CheckFrequency.ON_APP_RESUME
};

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu'.android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu'}); type Props = {};class App extends Component<Props> {
  // If there is an update prompt
  syncImmediate() {
    CodePush.sync( {
          // Install mode
          //ON_NEXT_RESUME the next time it returns to the foreground
          //ON_NEXT_RESTART The next restart
          //IMMEDIATE updates immediately
          mandatoryInstallMode : CodePush.InstallMode.IMMEDIATE ,
          deploymentKey: 'iOS platform Key, Production/Staging environment './ / dialog
          updateDialog : {
            // Whether to display the update description
            appendReleaseDescription : true ,
            // Update the description prefix. The default is "Description"
            descriptionPrefix : "Update:" ,
            // Forces the button text to be updated. The default is continue
            mandatoryContinueButtonLabel : "Update now" ,
            // Mandatory update information. The default is "An update is available that must be installed."
            mandatoryUpdateMessage : "Must be updated before use." ,
            // The text of the button is "ignore" by default.
            optionalIgnoreButtonLabel : 'later' ,
            // Confirm button text when not forced to update. The default is "Install"
            optionalInstallButtonLabel : 'Background Update' ,
            // The updated message text is checked when the update is not mandatory
            optionalUpdateMessage : 'There is a new version, is it up to date? ' ,
            // Title of the Alert window
            title : 'Update Prompt'}}); }componentWillMount() {
    CodePush.disallowRestart();// Disable restart
    this.syncImmediate(); // Start checking for updates
  }
  componentDidMount() {
    CodePush.allowRestart();// Restart is allowed after loading
  }
  
/ * or adopt a code componentDidMount () {CodePush. Sync ({updateDialog: {appendReleaseDescription: True, descriptionPrefix:'\n\n \ n 'and the title:' updated ', mandatoryUpdateMessage: ' ', mandatoryContinueButtonLabel: 'updated'}, MandatoryInstallMode: CodePush. InstallMode. IMMEDIATE, deploymentKey: 'iOS Key, the deployment environment (Production/Staging)',}); } * /
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>

        <Text style={styles.instructions}>This is the newer version</Text>
      </View>); }}// This line must be written
App = CodePush(codePushOptions)(App)

export default App

const styles = StyleSheet.create({
  container: {
    flex: 1.justifyContent: 'center'.alignItems: 'center'.backgroundColor: '#F5FCFF',},welcome: {
    fontSize: 20.textAlign: 'center'.margin: 10,},instructions: {
    textAlign: 'center'.color: '# 333333'.marginBottom: 5,}})Copy the code
  • Modify js file content at will, execute the package push command, you can see the content of hot update changes
Code-push releas-react sunny635533/DigitalMine -android Android -m true -d Staging --des "Staging" -t "1.0.0"Copy the code

Use Sequel Pro to view the contents of the code-push-server database

4.1 Database Tools

Download Sequel Pro, a lightweight database visualization tool

4.2 Connecting a Database

Five, Linux build to use the command

5.1 Text Editing on Linux Terminals

1、vim /etc/profile

2. Edit Press I to enter the edit mode. Enter colon: key, enter. Press Esc to enter the command mode. 4. Save enter the colon: key and press X to enter the save mode. 5

5.2 Starting the Service

Run./bin/ WWW

Check whether the port is used: lsof -i TCP :3000 3. Exit, exit 4, check the Linux current process ps aux | grep node 5, kill the specified process kill 9 6913 6, start the service and permanent process nohup. / bin/WWW &

Six, reference

  • The process of deploying code-push-server using Microsoft Code Push and privatization
  • Code – push – server’s official website
  • Docker deployment code – push – server