/src/test/com/mongodb/ReplSetTest.java

https://github.com/greenlaw110/mongo-java-driver · Java · 100 lines · 68 code · 15 blank · 17 comment · 7 complexity · e57bee2c97855b5eaa7fb45d1d09990c MD5 · raw file

  1. // ReplSetTest.java
  2. /**
  3. * Copyright (C) 2008 10gen Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package com.mongodb;
  18. import java.util.*;
  19. public class ReplSetTest {
  20. static void _sleep()
  21. throws InterruptedException {
  22. //Thread.sleep( 500 );
  23. }
  24. static class R extends Thread {
  25. R( ServerAddress a ){
  26. _a = a;
  27. _mongo = new Mongo(a);
  28. _db = _mongo.getDB( "test" );
  29. _coll = _db.getCollection( "foo" );
  30. _coll.slaveOk();
  31. }
  32. public void run(){
  33. while ( true ){
  34. try {
  35. _sleep();
  36. _coll.findOne();
  37. }
  38. catch ( NullPointerException n ){
  39. n.printStackTrace();
  40. }
  41. catch ( Exception e ){
  42. System.out.println( _a + "\t" + e );
  43. }
  44. }
  45. }
  46. final ServerAddress _a;
  47. final Mongo _mongo;
  48. final DB _db;
  49. final DBCollection _coll;
  50. }
  51. public static void main( String args[] )
  52. throws Exception {
  53. boolean rs = true;
  54. List<ServerAddress> addrs = new ArrayList<ServerAddress>();
  55. if ( rs ){
  56. addrs.add( new ServerAddress( "localhost" , 27018 ) );
  57. addrs.add( new ServerAddress( "localhost" , 27019 ) );
  58. addrs.add( new ServerAddress( "localhost" , 27020 ) );
  59. addrs.add( new ServerAddress( "localhost" , 27021 ) );
  60. }
  61. Mongo m = rs ? new Mongo( addrs ) : new Mongo();
  62. DB db = m.getDB( "test" );
  63. DBCollection c = db.getCollection( "foo" );
  64. c.drop();
  65. c.insert( new BasicDBObject( "_id" , 17 ) );
  66. c.slaveOk();
  67. for ( ServerAddress a : addrs ){
  68. new R(a).start();
  69. }
  70. while ( true ){
  71. _sleep();
  72. try {
  73. DBObject x = c.findOne(new BasicDBObject( "_id", 17 ), null);
  74. System.out.println( x );
  75. Integer n = (Integer) x.get( "x" );
  76. if (n != null && n >= 150 )
  77. break;
  78. c.update( new BasicDBObject( "_id", 17 ), new BasicDBObject( "$inc", new BasicDBObject( "x", 1 ) ) );
  79. }
  80. catch ( Exception e ){
  81. e.printStackTrace();
  82. }
  83. }
  84. }
  85. }