欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于redis的消息推送+messengerjs-rails

程序员文章站 2022-07-15 20:15:14
...
添加redis纪录回调:
class Notification < ApplicationRecord
  def read!
    self.read_at = Time.now
    self.save
  end

  belongs_to :operator, :class_name => "Employee", :foreign_key => "operator_id"
  default_scope ->{where("read_at is null")}

  before_create :add_redis_message

  def add_redis_message
    message_hash = Redis::HashKey.new("employee_#{self.employee_id}")
    message_hash["#{self.link}"] = "#{self.msg}"
  end

end


class Admin::NotificationsController < Admin::BaseController
  include ExemptedFromLogging
  
  def index
    employee_id = current_employee.id
    redis = Redis::HashKey.new("employee_#{employee_id}")
    if redis.blank?
      render :json=> nil
    else
      render :json=> redis.to_json
    end
  end

  def show_massage
    employee_id = current_employee.id
    redis = Redis::HashKey.new("employee_#{employee_id}")
    redis.delete(params[:url])
    redirect_to params[:url]
  end

end


在aplication.js中添加:
//= require messenger
//= require messenger-theme-future

Messenger.options = {
  extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right',
  theme: 'block',
  messageDefaults: {
    showCloseButton: true,
    hideAfter: 0
  }
}

var refreshMessages =  (function(){
  return function(){
    $.get('/admin/notifications', function(response){
      $.each(response, function() {
        var _this = this;
        var url = this.toString().split(",")[0]
        var value = this.toString().split(",")[1]
        var attr = { message: '[url=/admin/notifications/show_massage?url='+url+']' + value + '[/url]', type: 'info' ,id:value};
        Messenger().post(attr);
      });
    }, 'json');
  }
})();
var startRefreshMessages = function(){
  refreshMessages();
  setInterval(refreshMessages, 5 * 1000);
}



layout 中引入:

   <script type="text/javascript">
      <% if !Rails.env.development? %>
        startRefreshMessages();
      <% end %>
   </script>


gem requie

  gem "messengerjs-rails", "~> 1.4.1"
相关标签: redis