订阅所有JSP/Servlet的日志 订阅 | 这是最新一篇日志 上一篇 | 下一篇日志 下一篇 ]
NOSQL

using Hadoop to Cassandra through Binary Memtable

http://github.com/lenn0x/Cassandra-Hadoop-BMT/blob/master/src/java/org/digg/CassandraBulkLoader.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
*  Copyright (c) 2009, Chris Goffinet
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
*  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
 /**
  * Basic Hadoop to Cassandra example
  *
  * Author : Chris Goffinet (goffinet@digg.com)
  */
  
package org.digg;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
 
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.Column;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.dht.BigIntegerToken;
import org.apache.cassandra.io.DataOutputBuffer;
import org.apache.cassandra.net.EndPoint;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.net.SelectorManager;
import org.apache.cassandra.service.StorageService;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;
 
public class CassandraBulkLoader {
    public static class Map extends MapReduceBase implements Mapper<Text, Text, Text, Text> {
        private Text word = new Text();
 
        public void map(Text key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
            // This is a simple key/value mapper.
            output.collect(key, value);
        }
    }
    public static class Reduce extends MapReduceBase implements Reducer<Text, Text, Text, Text> {
        private Path[] localFiles;
        private ArrayList<String> tokens = new ArrayList<String>();
        private JobConf jobconf;
 
        public void configure(JobConf job) {
            this.jobconf = job;
            String cassConfig;
 
            // Get the cached files
            try
            {
                localFiles = DistributedCache.getLocalCacheFiles(job);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            cassConfig = localFiles[0].getParent().toString();
 
            System.setProperty("storage-config",cassConfig);
 
            startMessagingService();
            /* 
              Populate tokens 
              
              Specify your tokens and ips below. 
              
              tokens.add("0:192.168.0.1")
              tokens.add("14178431955039102644307275309657008810:192.168.0.2")
            */
 
            for (String token : this.tokens)
            {
                String[] values = token.split(":");
                StorageService.instance().updateTokenMetadata(new BigIntegerToken(new BigInteger(values[0])),new EndPoint(values[1], 7000));
            }
        }
        public void close()
        {
            try
            {
                // release the cache
                DistributedCache.releaseCache(new URI("/cassandra/storage-conf.xml#storage-conf.xml"), this.jobconf);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            catch (URISyntaxException e)
            {
                throw new RuntimeException(e);
            }
            shutdownMessagingService();
        }
        public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException
        {
            ColumnFamily columnFamily;
            String Keyspace = "Godspace";
            String CFName = "MyBigAdventureWithBob";
            Message message;
            List<ColumnFamily> columnFamilies;
            columnFamilies = new LinkedList<ColumnFamily>();
            String line;
 
            /* Create a column family */
            columnFamily = ColumnFamily.create(Keyspace, CFName);
            while (values.hasNext()) {
                // Split the value (line based on your own delimiter)
                line = values.next().toString();
                String[] fields = line.split("\1");
                columnFamily.addColumn(new QueryPath(CFName, fields[1].getBytes("UTF-8"), fields[2].getBytes("UTF-8")),fields[3].getBytes(),0);
            }
 
            columnFamilies.add(columnFamily);
 
            /* Get serialized message to send to cluster */
            message = createMessage(Keyspace, key.toString(), CFName, columnFamilies);
            for (EndPoint endpoint: StorageService.instance().getNStorageEndPoint(key.toString()))
            {
                /* Send message to end point */
                MessagingService.getMessagingInstance().sendOneWay(message, endpoint);
            }
            
            output.collect(key, new Text(" inserted into Cassandra node(s)"));
 
        }
    }
 
    public static void runJob(String[] args)
    {
        JobConf conf = new JobConf(CassandraBulkLoader.class);
 
        if(args.length >= 4)
        {
          conf.setNumReduceTasks(new Integer(args[3]));
        }
 
        try
        {
            // We store the cassandra storage-conf.xml on the HDFS cluster
            DistributedCache.addCacheFile(new URI("/cassandra/storage-conf.xml#storage-conf.xml"), conf);
        }
        catch (URISyntaxException e)
        {
            throw new RuntimeException(e);
        }
        conf.setInputFormat(KeyValueTextInputFormat.class);
        conf.setJobName("CassandraBulkLoader_v2");
        conf.setMapperClass(Map.class);
        conf.setReducerClass(Reduce.class);
 
        conf.setOutputKeyClass(Text.class);
        conf.setOutputValueClass(Text.class);
 
        FileInputFormat.setInputPaths(conf, new Path(args[1]));
        FileOutputFormat.setOutputPath(conf, new Path(args[2]));
        try
        {
            JobClient.runJob(conf);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    public static Message createMessage(String Keyspace, String Key, String CFName, List<ColumnFamily> ColumnFamiles)
    {
        ColumnFamily baseColumnFamily;
        DataOutputBuffer bufOut = new org.apache.cassandra.io.DataOutputBuffer();
        RowMutation rm;
        Message message;
        Column column;
 
        /* Get the first column family from list, this is just to get past validation */
        baseColumnFamily = new ColumnFamily(CFName, "Standard",DatabaseDescriptor.getComparator(Keyspace, CFName), DatabaseDescriptor.getSubComparator(Keyspace, CFName));
        
        for(ColumnFamily cf : ColumnFamiles) {
            bufOut.reset();
            try
            {
                ColumnFamily.serializer().serializeWithIndexes(cf, bufOut);
                byte[] data = new byte[bufOut.getLength()];
                System.arraycopy(bufOut.getData(), 0, data, 0, bufOut.getLength());
 
                column = new Column(cf.name().getBytes("UTF-8"), data, 0, false);
                baseColumnFamily.addColumn(column);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
        }
        rm = new RowMutation(Keyspace,StorageService.getPartitioner().decorateKey(Key));
        rm.add(baseColumnFamily);
 
        try
        {
            /* Make message */
            message = rm.makeRowMutationMessage(StorageService.binaryVerbHandler_);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
 
        return message;
    }
    public static void startMessagingService()
    {
        SelectorManager.getSelectorManager().start();
    }
    public static void shutdownMessagingService()
    {
        try
        {
            // Sleep just in case the number of keys we send over is small
            Thread.sleep(3*1000);
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }
        // Not implemented in Cassandra trunk, patch forth coming
        MessagingService.flushAndshutdown();
    }
    public static void main(String[] args) throws Exception
    {
        runJob(args);
    }
}


平均得分
(0 次评分)





文章来自: gitub
标签: hadoop cassandra NOSQL 
评论: 7 | 查看次数: 944
  • 共有 7 条评论
yanlink [2010-07-23 17:24:44]
kuailele [2010-07-23 16:19:51]
Ich hatte mir mehr erhofft von Schumacher. Ich bin etwas entt?uscht von seiner Leistung“, sagt Thomas
cheap true religion online sale
Mutschler, der ganz vorne an der Barriere steht und der mit dieser Meinung nicht alleine dasteht. Der louis vuitton Geldboersen

Diplom-Ingenieur aus Holzgerlingen hofft auf das kommende Jahr und auf eine gute Leistung in Hockenheim:

?Ich habe mir schon im letzten Jahr die Karten gekauft und werde hingehen, auch wenn Schumacher gerade

nicht so gut f?hrt.
gh1987117 [2010-06-07 15:45:59]
Willkommen auf level wow Website
Wir stellen alle wow lvl Dienstleistungen
Wir stellen wow lvl Dienstleistungen
Willkommen auf wow leveling Website
huiru [2010-06-01 16:52:48]
uggbootscheap [2010-05-20 17:11:00]
The success and downfalls you experience nike air max 91 help to create who you are and who you become . 20 MAY ZZY Even the bad experiences can be learned from puma running shoes.In fact,they are probably the most nike airmax 95 poignant and important ones.If someone hurts you ,betrays you ,or breaks your heart ,forgive them ,for they have helpedyou learn about nike silver air max 97 trust and the importance of being cautious when you open your lacoste men shoes heart .If someone loves you ,love them back unconditionally,not only womens nike air max 360 because they love you,but because in a way ,they are teaching you what to love and how to open your heart and eyes to things.Make every day count .Appreciate every moment and take from those nike air max 29 moments everything that you possibly can ,for you may never be able to experience timberland 6 inch boots it again.
uggbootscheap [2010-04-30 19:48:30]
With friendship, mbt shoes review life is happy and harmonious. Without friendship, life is hostile and unfortunate. I have friends in the rank and mbt chapa azul file. Some are rich and in power. Some are low and common. Some are like myself, working as a teacher, reading and writing and content with the simple mbt sport black life we have. To many of my friends, I know what to treasure, what to tolerate and what to share mbt sport white , I will never forget my old friends and keep making new friends. I will not he cold and indifferent to the poor friends and will show mbt lami black concern for them, even if it is only a comforting mbt walk black word.As life is full of strife and conflict, we need friends to support and help as out of difficulties. Our frinods give us warnings against danger. True friends share not only joy but, more often than not, they share mbt m walk silver sorrow. 30 April LH
uggbootscheap [2010-04-10 22:03:03]
100410SLLHI'm very glad to have received timberland roll tops letter you sent me two weeks ago. I' ve been thinking about cheap timberland boots question you asked me. In my opinion, you should come back after you finish your studies abroad.For one white timberland boots reason, what you are studying is badly needed nowadays in usa. It will be quite easy for you to find a good pink timberland boots job. In fact, I know a few big companies in our city are hoping to employ people like you. For another womens timberland boots reason, I think it will be much more convenient for you to look after your timberland kids shoes parents as they are getting old. Therefore, I think it's a good chukka boots men idea for you to return. So what are you waiting for mens 6 inch timberland boots?
  • 共有 7 条评论
发表评论
昵 称:  登录
内 容:
选 项:
字数限制 1000 字 | UBB代码 开启 | [img]标签 开启