将数据从服务器端同步到手机上, 并且需要离线工作,Couchebase Mobile 也许是目前最好的解决方案:

简介: 将数据从服务器端同步到手机上, 并且需要离线工作,Couchebase Mobile 也许是目前最好的解决方案: 原文地址: https://www.infinum.co/the-capsized-eight/articles/server-client-syncing-for-mobile-a...

将数据从服务器端同步到手机上, 并且需要离线工作,Couchebase Mobile 也许是目前最好的解决方案:

原文地址:

https://www.infinum.co/the-capsized-eight/articles/server-client-syncing-for-mobile-apps-using-couchbase-mobile

 

If you're developing a content rich application that synchronizes data from server to smartphone and needs to work offline, this is the article for you.

Every once in a while, you end up working on a project that throws you out of your comfort zone and requires some heavy duty learning.

For me, it was a seemingly simple project that required things like data replication and high availability, things I vaguely remember from my college days. After some exploring, I came across Couchbase Mobile, a framework that offers support for mobile app development and covers all of the requirements.

Couchbase Mobile has two major parts:

  • Couchbase Lite - an embedded, schemaless, JSON database
  • Sync Gateway - a mechanism to sync data to and from the server

Couchbase Mobile server-client syncing

NOSQL

Couchbase Lite is a NOSQL database, which means that there's no schema or a predefined data structure. It's a document store and the documents are JSON objects. It also means that you don't need to worry about structural changes in the data, since there's little structure to begin with. This allows for great flexibility and little maintenance.

VIEWS

If you need to build reports, aggregate and join documents, or have different representations of the data, you can use views. Views are defined in JavaScript. They are built dynamically and don't affect the underlying data, so you can have as many as you like.

DISTRIBUTION

Couchbase's distribution system is incredibly complex and very powerful. It has several main characteristics, and you can fine tune your app to use any or all of them:

  • Master → Slave replication
  • Master ↔ Master replication
  • Filtered Replication
  • Incremental and bi-directional replication
  • Conflict management

NETWORK AVAILABILITY

Additionally, you don't need to take care of the changes in the network availability. The underlying network listener in the library monitors the changes, and pauses and resumes whatever replication you have running, leaving you ample space to notify the user of the current network status.

Replication itself can be one-shot or continuous. If you want to say when and what needs to be synced to or from the host, you will use one-shot replication. On the other hand, if the requirements say that data should be synced anytime a change occurs, then continuous replication is the way to go. Both replications will download the same data, but keeping continuous replication running requires minimal data traffic, in my case less than 100 kB/h.

How do I implement it?

After we've covered the basics, let's see just how simple setting up an app with Couchbase Lite is. The official getting started pages are quite detailed and easy to follow. In the following example, I use the Cloudant service as the backend for my demo application, but you can setup your own host with CouchDb on it.

Here is a code example of the bare minimum needed to implement bidirectional replication from your Android application;

1. Add the repository location to the application's root build.gradle file

buildscript {
    repositories {
        mavenCentral()
        maven {
            url "http://files.couchbase.com/maven2/"
        }
        mavenLocal()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.9.+'
    }
}

allprojects {
    repositories {
        mavenCentral()
        maven {
            url "http://files.couchbase.com/maven2/"
        }
    }
}

2. Add the dependency to the module's build.gradle file

compile 'com.couchbase.lite:couchbase-lite-android:1.0.0'

3. Add the following code to your application's main activity or fragment

//initialise the database
 protected void initDB() throws IOException, CouchbaseLiteException {
        // create the database manager with default options
        Manager manager = new Manager(new AndroidContext(MainActivity.this), Manager.DEFAULT_OPTIONS);

        // get or create the database with the provided name
        database = manager.getDatabase("demodb");

        // add a change listener
        database.addChangeListener(databaseListener);
    }

//start bi-directional syncing
protected void startSync() {

        URL syncUrl;
        try {
            syncUrl = new URL("https://username:password" +
                    "@username.cloudant.com/demodb");
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

        // server - client 
        Replication pullReplication = database.createPullReplication(syncUrl);
        pullReplication.setContinuous(true);

        // client - server 
        Replication pushReplication = database.createPushReplication(syncUrl);
        pushReplication.setContinuous(true);

        // replication listeners
        pullReplication.addChangeListener(pullReplicationListener);
        pushReplication.addChangeListener(pushReplicationListener);

        // start both replications
        pullReplication.start();
        pushReplication.start();

    }

//call those methods in the onCreate
@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            initDB();
            startSync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The only thing left to do is to define some data in the database and show it to the users.

When to use Couchbase Mobile?

As always, you should find the best tool for the problem at hand. If your data is well structured and stable with no room for modification, then standard relational databases are the way to go.

If your data is flexible and should be available anytime and anywhere, this is by far the simplest solution.

目录
相关文章
|
4天前
|
安全 Linux 文件存储
如何在本地服务器部署TeslaMate并远程查看特斯拉汽车数据无需公网ip
如何在本地服务器部署TeslaMate并远程查看特斯拉汽车数据无需公网ip
|
4天前
|
定位技术
GPS北斗卫星同步时钟(时间同步服务器)建设施工部署方案
GPS北斗卫星同步时钟(时间同步服务器)建设施工部署方案
GPS北斗卫星同步时钟(时间同步服务器)建设施工部署方案
|
4天前
|
数据采集 中间件 Python
Scrapy爬虫:利用代理服务器爬取热门网站数据
Scrapy爬虫:利用代理服务器爬取热门网站数据
|
4天前
|
JSON Android开发 数据格式
android与Web服务器交互时的cookie使用-兼谈大众点评数据获得(原创)
android与Web服务器交互时的cookie使用-兼谈大众点评数据获得(原创)
21 2
|
2天前
|
数据采集 人工智能 自然语言处理
手机可跑,3.8B参数量超越GPT-3.5!微软发布Phi-3技术报告:秘密武器是洗干净数据
【5月更文挑战第16天】微软发布 Phi-3 技术报告,介绍了一个拥有3.8B参数的新语言模型,超越GPT-3.5,成为最大模型之一。 Phi-3 在手机上运行的特性开启了大型模型移动应用新纪元。报告强调数据清洗是关键,通过优化设计实现高效运行。实验显示 Phi-3 在多项NLP任务中表现出色,但泛化能力和数据隐私仍是挑战。该模型预示着AI领域的未来突破。[[论文链接](https://arxiv.org/pdf/2404.14219.pdf)]
11 2
|
4天前
|
存储 JSON JavaScript
Node.js 上开发一个 HTTP 服务器,监听某个端口,接收 HTTP POST 请求并处理传入的数据
Node.js 上开发一个 HTTP 服务器,监听某个端口,接收 HTTP POST 请求并处理传入的数据
13 0
|
4天前
|
存储 算法 数据挖掘
服务器数据恢复—拯救raid5阵列数据大行动,raid5数据恢复案例分享
**Raid5数据恢复算法原理:** 分布式奇偶校验的独立磁盘结构(被称之为raid5)的数据恢复有一个“奇偶校验”的概念。可以简单的理解为二进制运算中的“异或运算”,通常使用的标识是xor。运算规则:若二者值相同则结果为0,若二者结果不同则结果为1。 例如0101 xor 0010根据上述运算规则来计算的话二者第一位都是0,两者相同,结果为0 ;第二、三、四位的数值不同则结果均为1,所以最终结果为0111。公式表示为:0101 xor 0010 = 0111,所以在 a xor b=c 中如果缺少其中之一,我们可以通过其他数据进行推算,这就是raid5数据恢复的基本原理。 了解了这个基本原理
|
4天前
LabVIEW使用VI服务器的调用节点将数据传递到另一个VI 使用调用节点(Invoke Node)与通过引用调用节点(Call by Reference)调用VI时有什么差别?
LabVIEW使用VI服务器的调用节点将数据传递到另一个VI 使用调用节点(Invoke Node)与通过引用调用节点(Call by Reference)调用VI时有什么差别?
|
4天前
|
机器学习/深度学习 数据采集 数据可视化
R语言SVM模型文本挖掘分类研究手机评论数据词云可视化
R语言SVM模型文本挖掘分类研究手机评论数据词云可视化
|
4天前
|
监控 安全 持续交付
【专栏】Webhook是服务器主动发送事件通知的机制,打破传统客户端轮询模式,实现数据实时高效传递。
【4月更文挑战第29天】Webhook是服务器主动发送事件通知的机制,打破传统客户端轮询模式,实现数据实时高效传递。常用于持续集成部署、第三方服务集成、实时数据同步和监控告警。具有实时性、高效性和灵活性优势,但也面临安全风险和调试挑战。理解并善用Webhook能提升系统性能,广泛应用于现代软件开发和集成。

热门文章

最新文章