dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/adaptivesvc/limiter_mapper.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * 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, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package adaptivesvc 19 20 import ( 21 "fmt" 22 "sync" 23 ) 24 25 import ( 26 "dubbo.apache.org/dubbo-go/v3/common" 27 "dubbo.apache.org/dubbo-go/v3/filter/adaptivesvc/limiter" 28 ) 29 30 var ( 31 limiterMapperSingleton *limiterMapper 32 33 ErrLimiterNotFoundOnMapper = fmt.Errorf("limiter not found on mapper") 34 ErrLimiterTypeNotFound = fmt.Errorf("limiter type not found") 35 ) 36 37 func init() { 38 limiterMapperSingleton = newLimiterMapper() 39 } 40 41 type limiterMapper struct { 42 rwMutex *sync.RWMutex 43 mapper map[string]limiter.Limiter 44 } 45 46 func newLimiterMapper() *limiterMapper { 47 return &limiterMapper{ 48 rwMutex: new(sync.RWMutex), 49 mapper: make(map[string]limiter.Limiter), 50 } 51 } 52 53 func (m *limiterMapper) newAndSetMethodLimiter(url *common.URL, methodName string, limiterType int) (limiter.Limiter, error) { 54 key := fmt.Sprintf("%s%s", url.Path, methodName) 55 56 var ( 57 l limiter.Limiter 58 ok bool 59 ) 60 m.rwMutex.Lock() 61 defer m.rwMutex.Unlock() 62 63 if l, ok = limiterMapperSingleton.mapper[key]; ok { 64 return l, nil 65 } 66 switch limiterType { 67 case limiter.HillClimbingLimiter: 68 l = limiter.NewHillClimbing() 69 default: 70 return nil, ErrLimiterTypeNotFound 71 } 72 limiterMapperSingleton.mapper[key] = l 73 return l, nil 74 } 75 76 func (m *limiterMapper) getMethodLimiter(url *common.URL, methodName string) ( 77 limiter.Limiter, error) { 78 key := fmt.Sprintf("%s%s", url.Path, methodName) 79 m.rwMutex.RLock() 80 l, ok := limiterMapperSingleton.mapper[key] 81 m.rwMutex.RUnlock() 82 if !ok { 83 return nil, ErrLimiterNotFoundOnMapper 84 } 85 return l, nil 86 }