extension.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. 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,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #ifndef BRPC_EXTENSION_H
  18. #define BRPC_EXTENSION_H
  19. #include <string>
  20. #include "butil/scoped_lock.h"
  21. #include "butil/logging.h"
  22. #include "butil/containers/case_ignored_flat_map.h"
  23. #include "butil/memory/singleton_on_pthread_once.h"
  24. namespace butil {
  25. template <typename T> class GetLeakySingleton;
  26. }
  27. namespace brpc {
  28. // A global map from string to user-extended instances (typed T).
  29. // It's used by NamingService and LoadBalancer to maintain globally
  30. // available instances.
  31. // All names are case-insensitive. Names are printed in lowercases.
  32. template <typename T>
  33. class Extension {
  34. public:
  35. static Extension<T>* instance();
  36. int Register(const std::string& name, T* instance);
  37. int RegisterOrDie(const std::string& name, T* instance);
  38. T* Find(const char* name);
  39. void List(std::ostream& os, char separator);
  40. private:
  41. friend class butil::GetLeakySingleton<Extension<T> >;
  42. Extension();
  43. ~Extension();
  44. butil::CaseIgnoredFlatMap<T*> _instance_map;
  45. butil::Mutex _map_mutex;
  46. };
  47. } // namespace brpc
  48. #include "brpc/extension_inl.h"
  49. #endif // BRPC_EXTENSION_H