OSDN Git Service

add Plugin::Statics
authorhylom <hylom@users.sourceforge.jp>
Sun, 15 Oct 2017 13:27:40 +0000 (22:27 +0900)
committerhylom <hylom@users.sourceforge.jp>
Sun, 15 Oct 2017 13:27:40 +0000 (22:27 +0900)
src/newslash_web/lib/Newslash/Plugin/Statics.pm [new file with mode: 0644]
src/newslash_web/lib/Newslash/Web.pm

diff --git a/src/newslash_web/lib/Newslash/Plugin/Statics.pm b/src/newslash_web/lib/Newslash/Plugin/Statics.pm
new file mode 100644 (file)
index 0000000..011f128
--- /dev/null
@@ -0,0 +1,53 @@
+package Newslash::Plugin::Statics;
+use Mojo::Base 'Mojolicious::Plugin';
+
+use constant KEY_PREFIX => "newslash_statics:";
+use constant KEY_REQUEST_COUNTER => "req_count";
+use constant REQUEST_COUNTER_BASE_TIME_FIELD => "base_time";
+
+sub register {
+    my ($self, $app, $conf) = @_;
+    $conf ||= {};
+    $self->{app} = $app;
+    $self->{kvs} = $app->kvs;
+    $self->{options} = $conf->{options} || {};
+
+    $app->hook(after_dispatch=> sub {
+                   my $c = shift;
+                   my $method = $c->req->method;
+                   my $code = $c->res->code;
+                   if (!$method || !$code) {
+                       $app->log->error("Plugin::Statics: update_request_counter error. method: $method, code: $code");
+                       return;
+                   }
+                   my $rs = $self->update_request_counter($method, $code);
+                   if (!defined $rs) {
+                       $app->log->error("Plugin::Statics: update_request_counter error. method: $method, code: $code");
+                   }
+                   #else {
+                   #    $app->log->info("Plugin::Statics: update_request_counter done. method: $method, code: $code");
+                   #}
+               });
+}
+
+sub update_request_counter {
+    my ($self, $method, $code) = @_;
+    my $key = KEY_PREFIX . KEY_REQUEST_COUNTER;
+    my $field_base_time = REQUEST_COUNTER_BASE_TIME_FIELD;
+    my $field = uc($method);
+    return if !$field || !$key;
+
+    my $kvs = $self->{kvs};
+    $kvs->start_transaction;
+
+    if (!$kvs->hexists($key, $field_base_time)) {
+        my $time = $kvs->time;
+        $kvs->hset($key, $field_base_time, $time->[0]);
+    }
+    $kvs->hincrby($key, $field, 1);
+    $kvs->commit;
+    return 1;
+}
+
+
+1;
index 442bf21..93125d5 100644 (file)
@@ -106,8 +106,8 @@ sub startup {
     # Event Que
     $app->plugin('Newslash::Plugin::EventQue');
 
-    # Request Logger
-    #$app->plugin('Newslash::Plugin::RequestLogger');
+    # Statics Logger
+    $app->plugin('Newslash::Plugin::Statics');
 
     ############################################################
     #