Last active
January 21, 2016 03:04
-
-
Save nz/f429ff521915bad0f8d6 to your computer and use it in GitHub Desktop.
RSolr with default headers for websolr preferential routing to master or slave
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Websolr can use HTTP headers to control authorization and request routing. | |
# This class injects a connection wrapper into Sunspot to set default headers | |
# on every request. | |
# | |
# Interesting values for X-Websolr-Routing: | |
# - prefer-master (route serches to master, for real-time search; cpu expensive; current default) | |
# - prefer-random (distribute searches evenly; for high-volume of searches relative to updates) | |
# - prefer-replica (isolate search requests from updates; for high-volumes of one type of traffic negatively impacting the other) | |
# | |
class RSolrWithDefaultHeaders | |
attr_accessor :default_headers | |
def initialize(default_headers = {}) | |
self.default_headers = default_headers | |
end | |
def connect(opts = {}) | |
RSolr::Client.new(ConnectionWithDefaultHeaders.new(default_headers), opts) | |
end | |
class ConnectionWithDefaultHeaders < ::RSolr::Connection | |
attr_accessor :default_headers | |
def initialize(default_headers) | |
self.default_headers = default_headers | |
end | |
def setup_raw_request_with_default_headers(request_context={}) | |
request_context[:headers] = request_context[:headers].merge(default_headers) | |
setup_raw_request_without_default_headers(request_context) | |
end | |
alias_method_chain :setup_raw_request, :default_headers | |
end | |
end | |
Sunspot::Session.connection_class = RSolrWithDefaultHeaders.new({ | |
'X-Websolr-Routing' => 'prefer-replica' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment