2 Incheckningar 46454becc3 ... 03adec571b

Upphovsman SHA1 Meddelande Datum
  zhangqian 03adec571b 添加jwt token校验 10 månader sedan
  zhangqian 66c91488b9 1.添加redis配置 2. 补足请求参数结构体 10 månader sedan
14 ändrade filer med 372 tillägg och 50 borttagningar
  1. 22 0
      app.log
  2. 10 0
      config/config.go
  3. 9 2
      config/config.prod.yaml
  4. 9 2
      config/config.yaml
  5. 45 0
      database/redis.go
  6. 14 12
      entity/metric_process_config.go
  7. 3 0
      go.mod
  8. 16 0
      go.sum
  9. 19 0
      main.go
  10. 44 33
      middleware/jwt.go
  11. 1 1
      routes/router.go
  12. 76 0
      service/redis.go
  13. 33 0
      utils/common.go
  14. 71 0
      utils/redis.go

+ 22 - 0
app.log

@@ -174,3 +174,25 @@ INFO: 2025/09/04 16:12:37 logger.go:53: Starting application...
 INFO: 2025/09/04 16:12:37 logger.go:53: Config loaded successfully
 INFO: 2025/09/04 16:12:37 logger.go:53: Config loaded successfully
 INFO: 2025/09/04 16:12:38 logger.go:53: Database initialized successfully
 INFO: 2025/09/04 16:12:38 logger.go:53: Database initialized successfully
 INFO: 2025/09/04 16:12:38 logger.go:53: Server starting on port 8080
 INFO: 2025/09/04 16:12:38 logger.go:53: Server starting on port 8080
+INFO: 2025/12/23 11:32:10 logger.go:53: Starting application...
+INFO: 2025/12/23 11:32:10 logger.go:53: Config loaded successfully
+INFO: 2025/12/23 18:36:15 logger.go:53: Starting application...
+INFO: 2025/12/23 18:36:15 logger.go:53: Config loaded successfully
+INFO: 2025/12/23 18:36:15 logger.go:53: Database initialized successfully
+INFO: 2025/12/23 18:36:15 logger.go:53: Redis initialized successfully
+INFO: 2025/12/23 18:36:15 logger.go:53: Server starting on port 8080
+INFO: 2025/12/23 18:39:45 logger.go:53: Starting application...
+INFO: 2025/12/23 18:39:45 logger.go:53: Config loaded successfully
+INFO: 2025/12/23 18:39:45 logger.go:53: Database initialized successfully
+INFO: 2025/12/23 18:39:45 logger.go:53: Redis initialized successfully
+INFO: 2025/12/23 18:39:45 logger.go:53: Server starting on port 8080
+INFO: 2025/12/23 18:41:15 logger.go:53: Starting application...
+INFO: 2025/12/23 18:41:15 logger.go:53: Config loaded successfully
+INFO: 2025/12/23 18:41:15 logger.go:53: Database initialized successfully
+INFO: 2025/12/23 18:41:15 logger.go:53: Redis initialized successfully
+INFO: 2025/12/23 18:41:15 logger.go:53: Server starting on port 8080
+INFO: 2025/12/23 18:41:58 logger.go:53: Starting application...
+INFO: 2025/12/23 18:41:58 logger.go:53: Config loaded successfully
+INFO: 2025/12/23 18:41:58 logger.go:53: Database initialized successfully
+INFO: 2025/12/23 18:41:58 logger.go:53: Redis initialized successfully
+INFO: 2025/12/23 18:41:58 logger.go:53: Server starting on port 8080

+ 10 - 0
config/config.go

@@ -23,9 +23,19 @@ type JWTConfig struct {
 	Expire int    `yaml:"expire"`
 	Expire int    `yaml:"expire"`
 }
 }
 
 
+// RedisConfig Redis配置
+type RedisConfig struct {
+	Host     string `yaml:"host"`
+	Port     int    `yaml:"port"`
+	Password string `yaml:"password"`
+	DB       int    `yaml:"db"`
+	PoolSize int    `yaml:"poolSize"`
+}
+
 // Config 配置结构体
 // Config 配置结构体
 type Config struct {
 type Config struct {
 	Server ServerConfig `yaml:"server"`
 	Server ServerConfig `yaml:"server"`
 	MySQL  MySQLConfig  `yaml:"mysql"`
 	MySQL  MySQLConfig  `yaml:"mysql"`
 	JWT    JWTConfig    `yaml:"jwt"`
 	JWT    JWTConfig    `yaml:"jwt"`
+	Redis  RedisConfig  `yaml:"redis"`
 }
 }

+ 9 - 2
config/config.prod.yaml

@@ -12,5 +12,12 @@ mysql:
   loc: Local
   loc: Local
 
 
 jwt:
 jwt:
-  secret: newaterobot_secret
-  expire: 3600
+  secret: ae0536f9-6450-4606-8e13-5a19ed505da0
+  expire: 3600
+
+redis:
+  host: 127.0.0.1
+  port: 6379
+  password: ""
+  db: 0
+  poolSize: 10

+ 9 - 2
config/config.yaml

@@ -12,5 +12,12 @@ mysql:
   loc: Local
   loc: Local
 
 
 jwt:
 jwt:
-  secret: newaterobot_secret
-  expire: 3600
+  secret: ae0536f9-6450-4606-8e13-5a19ed505da0
+  expire: 3600
+
+redis:
+  host: 127.0.0.1
+  port: 36379
+  password: G62m50oigI221107
+  db: 5
+  poolSize: 10

+ 45 - 0
database/redis.go

@@ -0,0 +1,45 @@
+package database
+
+import (
+	"context"
+	"fmt"
+	"time"
+
+	"github.com/go-redis/redis/v8"
+	
+	"newaterobot-process/config"
+)
+
+var RedisClient *redis.Client
+
+// InitRedis 初始化Redis连接
+func InitRedis() error {
+	redisConfig := config.GlobalConfig.Redis
+	
+	// 创建Redis客户端
+	RedisClient = redis.NewClient(&redis.Options{
+		Addr:     fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port),
+		Password: redisConfig.Password,
+		DB:       redisConfig.DB,
+		PoolSize: redisConfig.PoolSize,
+	})
+
+	// 测试连接
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	
+	_, err := RedisClient.Ping(ctx).Result()
+	if err != nil {
+		return fmt.Errorf("failed to connect to Redis: %v", err)
+	}
+
+	return nil
+}
+
+// CloseRedis 关闭Redis连接
+func CloseRedis() error {
+	if RedisClient != nil {
+		return RedisClient.Close()
+	}
+	return nil
+}

+ 14 - 12
entity/metric_process_config.go

@@ -20,18 +20,20 @@ func (m *MetricProcessConfig) TableName() string {
 }
 }
 
 
 type MetricProcessRequest struct {
 type MetricProcessRequest struct {
-	DateSrc    string `json:"date_src"`    //原始时间
-	DateTime   string `json:"datetime"`    //查询日期
-	STime      string `json:"s_time"`      //查询开始时间
-	ETime      string `json:"e_time"`      //查询结束时间
-	Intent     int    `json:"intent"`      //意图识别大类
-	MetricType int    `json:"metric_type"` //意图识别小类
-	Name       string `json:"name"`        //水厂名称
-	ID         int    `json:"id"`          //水厂id
-	LocalUrl   string `json:"local_url"`   //查询的url
-	Metric     string `json:"metric"`      //查询指标
-	JwtToken   string `json:"jwt_token"`
-	IsEnglish  int    `json:"is_english"`
+	DateSrc        string `json:"date_src"`    //原始时间
+	DateTime       string `json:"datetime"`    //查询日期
+	STime          string `json:"s_time"`      //查询开始时间
+	ETime          string `json:"e_time"`      //查询结束时间
+	Intent         int    `json:"intent"`      //意图识别大类
+	MetricType     int    `json:"metric_type"` //意图识别小类
+	Name           string `json:"name"`        //水厂名称
+	ID             int    `json:"id"`          //水厂id
+	LocalUrl       string `json:"local_url"`   //查询的url
+	Metric         string `json:"metric"`      //查询指标
+	JwtToken       string `json:"jwt_token"`
+	IsEnglish      int    `json:"is_english"`      //是否英文标识
+	ConversationId string `json:"conversation_id"` // 会话id
+	DialogueCount  string `json:"dialogue_count"`  // 对话次数
 }
 }
 type MetricProcessResponse struct {
 type MetricProcessResponse struct {
 	Flag         int    `json:"flag"` // 0 直接回复 1 http查询上下文 2 无须执行体执行的分支
 	Flag         int    `json:"flag"` // 0 直接回复 1 http查询上下文 2 无须执行体执行的分支

+ 3 - 0
go.mod

@@ -4,6 +4,7 @@ go 1.21
 
 
 require (
 require (
 	github.com/gin-gonic/gin v1.9.1
 	github.com/gin-gonic/gin v1.9.1
+	github.com/go-redis/redis/v8 v8.11.5
 	github.com/golang-jwt/jwt/v4 v4.5.0
 	github.com/golang-jwt/jwt/v4 v4.5.0
 	github.com/tidwall/gjson v1.18.0
 	github.com/tidwall/gjson v1.18.0
 	golang.org/x/crypto v0.11.0
 	golang.org/x/crypto v0.11.0
@@ -14,7 +15,9 @@ require (
 
 
 require (
 require (
 	github.com/bytedance/sonic v1.9.1 // indirect
 	github.com/bytedance/sonic v1.9.1 // indirect
+	github.com/cespare/xxhash/v2 v2.1.2 // indirect
 	github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
 	github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
+	github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
 	github.com/gabriel-vasile/mimetype v1.4.2 // indirect
 	github.com/gabriel-vasile/mimetype v1.4.2 // indirect
 	github.com/gin-contrib/sse v0.1.0 // indirect
 	github.com/gin-contrib/sse v0.1.0 // indirect
 	github.com/go-playground/locales v0.14.1 // indirect
 	github.com/go-playground/locales v0.14.1 // indirect

+ 16 - 0
go.sum

@@ -1,12 +1,18 @@
 github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
 github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
 github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
 github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
 github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
 github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
+github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
+github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
 github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
 github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
 github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
 github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
 github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
 github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
+github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
 github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
 github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
 github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
 github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
 github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
 github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
@@ -21,6 +27,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
 github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
 github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
 github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
 github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
 github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
 github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
+github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
+github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
 github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
 github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
 github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
 github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
 github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
 github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
@@ -49,6 +57,12 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
 github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
 github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
 github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
 github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
+github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
+github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
+github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
+github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
+github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
 github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
 github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
 github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
 github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@@ -94,6 +108,8 @@ google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cn
 google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
 google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
 gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
 gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
 gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
 gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
 gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

+ 19 - 0
main.go

@@ -22,6 +22,7 @@ func main() {
 	}
 	}
 	utils.Infof("Config loaded successfully")
 	utils.Infof("Config loaded successfully")
 
 
+	utils.SetJWTSecret()
 	// 初始化数据库
 	// 初始化数据库
 	err = database.InitDB()
 	err = database.InitDB()
 	if err != nil {
 	if err != nil {
@@ -29,6 +30,13 @@ func main() {
 	}
 	}
 	utils.Infof("Database initialized successfully")
 	utils.Infof("Database initialized successfully")
 
 
+	// 初始化Redis
+	err = database.InitRedis()
+	if err != nil {
+		log.Fatalf("Failed to initialize Redis: %v", err)
+	}
+	utils.Infof("Redis initialized successfully")
+
 	// 自动迁移数据库表
 	// 自动迁移数据库表
 	// err = database.DB.AutoMigrate(&entity.User{})
 	// err = database.DB.AutoMigrate(&entity.User{})
 	// if err != nil {
 	// if err != nil {
@@ -47,3 +55,14 @@ func main() {
 		log.Fatalf("Failed to start server: %v", err)
 		log.Fatalf("Failed to start server: %v", err)
 	}
 	}
 }
 }
+
+// 关闭程序时释放资源
+func init() {
+	// 确保在程序退出时关闭数据库连接
+	defer func() {
+		err := database.CloseRedis()
+		if err != nil {
+			log.Printf("Failed to close Redis: %v", err)
+		}
+	}()
+}

+ 44 - 33
middleware/jwt.go

@@ -1,53 +1,64 @@
 package middleware
 package middleware
 
 
 import (
 import (
-	"net/http"
-	"strings"
-	
 	"github.com/gin-gonic/gin"
 	"github.com/gin-gonic/gin"
-	
-	"newaterobot-process/service"
+	"github.com/golang-jwt/jwt/v4"
+	"net/http"
+	"newaterobot-process/utils"
 )
 )
 
 
 // JWTAuthMiddleware JWT认证中间件
 // JWTAuthMiddleware JWT认证中间件
 func JWTAuthMiddleware() gin.HandlerFunc {
 func JWTAuthMiddleware() gin.HandlerFunc {
 	return func(c *gin.Context) {
 	return func(c *gin.Context) {
-		// 获取token
-		authHeader := c.GetHeader("Authorization")
-		if authHeader == "" {
-			c.JSON(http.StatusUnauthorized, gin.H{
-				"code": 401,
-				"message": "请求未携带token,无权限访问",
-			})
-			c.Abort()
-			return
+
+		if c.Keys == nil {
+			c.Keys = make(map[string]any)
+		}
+		//判断
+		var code int
+		var data interface{}
+		code = http.StatusOK
+		//分别从Header和Query Param当中获取 jwt-token
+		token := c.GetHeader("JWT-TOKEN")
+		if token == "" {
+			token = c.Query("JWT-TOKEN")
 		}
 		}
 
 
-		// 按空格分割
-		parts := strings.SplitN(authHeader, " ", 2)
-		if !(len(parts) == 2 && parts[0] == "Bearer") {
-			c.JSON(http.StatusUnauthorized, gin.H{
-				"code": 401,
-				"message": "请求头中auth格式有误",
-			})
-			c.Abort()
-			return
+		// session未中断
+		if _, ok := c.Keys[utils.SessionUserIdKey]; ok {
+			c.Next()
+		}
+
+		if token == "" {
+			code = http.StatusUnauthorized
+			data = "无法获取token参数"
+		} else {
+			claim, err := utils.ParseTokenWithDep(token)
+			if err != nil {
+				switch err.(*jwt.ValidationError).Errors {
+				case jwt.ValidationErrorExpired:
+					code = http.StatusUnauthorized
+				default:
+					code = http.StatusUnauthorized
+				}
+			}
+
+			if code == http.StatusOK {
+				c.Keys[utils.SessionUserIdKey] = claim.ID
+				c.Keys[utils.SessionDepIdKey] = claim.Dep
+			}
 		}
 		}
 
 
-		// 解析token
-		claims, err := service.GetJWTService().ParseToken(parts[1])
-		if err != nil {
+		if code != http.StatusOK {
 			c.JSON(http.StatusUnauthorized, gin.H{
 			c.JSON(http.StatusUnauthorized, gin.H{
-				"code": 401,
-				"message": "token无效或已过期",
+				"code": code,
+				"msg":  "token 验证失败",
+				"data": data,
 			})
 			})
+
 			c.Abort()
 			c.Abort()
 			return
 			return
 		}
 		}
-
-		// 将用户信息保存到上下文
-		c.Set("user_id", claims.UserID)
-		c.Set("username", claims.Username)
 		c.Next()
 		c.Next()
 	}
 	}
-}
+}

+ 1 - 1
routes/router.go

@@ -16,13 +16,13 @@ func InitRouter() *gin.Engine {
 	{
 	{
 		public.POST("/register", handler.Register)
 		public.POST("/register", handler.Register)
 		public.POST("/login", handler.Login)
 		public.POST("/login", handler.Login)
-		public.POST("/metric_process", handler.MetricProcess)
 	}
 	}
 
 
 	// 需要认证的路由
 	// 需要认证的路由
 	private := r.Group("/api/v1")
 	private := r.Group("/api/v1")
 	private.Use(middleware.JWTAuthMiddleware())
 	private.Use(middleware.JWTAuthMiddleware())
 	{
 	{
+		private.POST("/metric_process", handler.MetricProcess)
 		private.GET("/user/info", handler.GetUserInfo)
 		private.GET("/user/info", handler.GetUserInfo)
 	}
 	}
 
 

+ 76 - 0
service/redis.go

@@ -0,0 +1,76 @@
+package service
+
+import (
+	"encoding/json"
+	"time"
+
+	"newaterobot-process/utils"
+)
+
+// RedisService Redis服务
+type RedisService struct {
+	redisUtil *utils.RedisUtil
+}
+
+var redisService = new(RedisService)
+
+// NewRedisService 创建Redis服务实例
+func NewRedisService() *RedisService {
+	return &RedisService{
+		redisUtil: utils.GetRedisUtil(),
+	}
+}
+
+// GetRedisService 获取Redis服务实例
+func GetRedisService() *RedisService {
+	return redisService
+}
+
+// SetString 设置字符串值
+func (r *RedisService) SetString(key, value string, expiration time.Duration) error {
+	return r.redisUtil.SetString(key, value, expiration)
+}
+
+// GetString 获取字符串值
+func (r *RedisService) GetString(key string) (string, error) {
+	return r.redisUtil.GetString(key)
+}
+
+// SetObject 设置对象值
+func (r *RedisService) SetObject(key string, obj interface{}, expiration time.Duration) error {
+	return r.redisUtil.SetObject(key, obj, expiration)
+}
+
+// GetObject 获取对象值
+func (r *RedisService) GetObject(key string, obj interface{}) error {
+	return r.redisUtil.GetObject(key, obj)
+}
+
+// Exists 检查键是否存在
+func (r *RedisService) Exists(key string) (bool, error) {
+	return r.redisUtil.Exists(key)
+}
+
+// Del 删除键
+func (r *RedisService) Del(key string) error {
+	return r.redisUtil.Del(key)
+}
+
+// SetExpire 设置带过期时间的键值对
+func (r *RedisService) SetExpire(key string, value interface{}, expiration time.Duration) error {
+	return r.redisUtil.SetExpire(key, value, expiration)
+}
+
+// GetAndDecode 获取并解码JSON对象
+func (r *RedisService) GetAndDecode(key string, dest interface{}) error {
+	data, err := r.redisUtil.GetString(key)
+	if err != nil {
+		return err
+	}
+	return json.Unmarshal([]byte(data), dest)
+}
+
+// Increment 增加计数器
+func (r *RedisService) Increment(key string) error {
+	return utils.GetRedisUtil().SetExpire(key, 1, time.Hour)
+}

+ 33 - 0
utils/common.go

@@ -3,10 +3,43 @@ package utils
 import (
 import (
 	"crypto/md5"
 	"crypto/md5"
 	"fmt"
 	"fmt"
+	"github.com/golang-jwt/jwt/v4"
+	"newaterobot-process/config"
 	"regexp"
 	"regexp"
 	"strings"
 	"strings"
 )
 )
 
 
+const (
+	SessionUserIdKey = "uid"
+	SessionDepIdKey  = "dep"
+)
+
+type ClaimsDep struct {
+	ID       int
+	Username string
+	Dep      string
+	jwt.StandardClaims
+}
+
+var jwtSecret []byte
+
+func SetJWTSecret() {
+	jwtSecret = []byte(config.GlobalConfig.JWT.Secret)
+}
+func ParseTokenWithDep(token string) (*ClaimsDep, error) {
+	tokenClaims, err := jwt.ParseWithClaims(token, &ClaimsDep{}, func(token *jwt.Token) (interface{}, error) {
+		return jwtSecret, nil
+	})
+
+	if tokenClaims != nil {
+		if claims, ok := tokenClaims.Claims.(*ClaimsDep); ok && tokenClaims.Valid {
+			return claims, nil
+		}
+	}
+
+	return nil, err
+}
+
 // MD5 字符串MD5加密
 // MD5 字符串MD5加密
 func MD5(s string) string {
 func MD5(s string) string {
 	data := []byte(s)
 	data := []byte(s)

+ 71 - 0
utils/redis.go

@@ -0,0 +1,71 @@
+package utils
+
+import (
+	"context"
+	"encoding/json"
+	"time"
+
+	"newaterobot-process/database"
+)
+
+// RedisUtil Redis工具类
+type RedisUtil struct{}
+
+var redisUtil = new(RedisUtil)
+
+// GetRedisUtil 获取Redis工具实例
+func GetRedisUtil() *RedisUtil {
+	return redisUtil
+}
+
+// SetString 设置字符串值
+func (r *RedisUtil) SetString(key, value string, expiration time.Duration) error {
+	return database.RedisClient.Set(context.Background(), key, value, expiration).Err()
+}
+
+// GetString 获取字符串值
+func (r *RedisUtil) GetString(key string) (string, error) {
+	return database.RedisClient.Get(context.Background(), key).Result()
+}
+
+// SetObject 设置对象值
+func (r *RedisUtil) SetObject(key string, obj interface{}, expiration time.Duration) error {
+	jsonData, err := json.Marshal(obj)
+	if err != nil {
+		return err
+	}
+	return database.RedisClient.Set(context.Background(), key, jsonData, expiration).Err()
+}
+
+// GetObject 获取对象值
+func (r *RedisUtil) GetObject(key string, obj interface{}) error {
+	jsonData, err := database.RedisClient.Get(context.Background(), key).Result()
+	if err != nil {
+		return err
+	}
+	return json.Unmarshal([]byte(jsonData), obj)
+}
+
+// Exists 检查键是否存在
+func (r *RedisUtil) Exists(key string) (bool, error) {
+	count, err := database.RedisClient.Exists(context.Background(), key).Result()
+	if err != nil {
+		return false, err
+	}
+	return count > 0, nil
+}
+
+// Del 删除键
+func (r *RedisUtil) Del(key string) error {
+	return database.RedisClient.Del(context.Background(), key).Err()
+}
+
+// Expire 设置键过期时间
+func (r *RedisUtil) Expire(key string, expiration time.Duration) error {
+	return database.RedisClient.Expire(context.Background(), key, expiration).Err()
+}
+
+// SetExpire 设置带过期时间的键值对
+func (r *RedisUtil) SetExpire(key string, value interface{}, expiration time.Duration) error {
+	return database.RedisClient.SetEX(context.Background(), key, value, expiration).Err()
+}