@Service
public class ResourceService {
@SentinelResource ( value = "doGetResource" , blockHandlerClass = ResourceBlockHandler . class , blockHandler = "call" )
public String doGetResource ( ) {
return "This is test03" ;
}
}
@Component
@Slf4j
public class ResourceBlockHandler {
public static String call ( BlockException e) {
log. error ( e. getMessage ( ) ) ;
return "别点了!" ;
}
}
@GetMapping ( "sentinel03" )
public String doSentinel03 ( ) {
String s = resourceService. doGetResource ( ) ;
return s;
}
private AtomicLong atomicLong = new AtomicLong ( 1 ) ;
@GetMapping ( "sentinel04" )
public String doSentinel04 ( ) throws InterruptedException {
long num = atomicLong. getAndIncrement ( ) ;
if ( num% 2 == 0 ) {
Thread . sleep ( 200 ) ;
}
return "Sentinel Test04~~~" ;
}
@Component
@Slf4j
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle ( HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
response. setCharacterEncoding ( "utf-8" ) ;
response. setContentType ( "text/html;charset=utf-8" ) ;
Map < String , Object > map = new HashMap < > ( ) ;
map. put ( "status" , 429 ) ;
map. put ( "message" , "频繁访问" ) ;
String jsonstr = new ObjectMapper ( ) . writeValueAsString ( map) ;
PrintWriter out = response. getWriter ( ) ;
out. print ( jsonstr) ;
out. flush ( ) ;
out. close ( ) ;
}
}
@GetMapping ( "/sentinel/findById" )
@SentinelResource ( "resource" )
public String doFindById ( @RequestParam ( "id" ) Integer id) {
return "resource id is " + id;
}
@Component
public class DefaultRequestOriginParser implements RequestOriginParser {
@Override
public String parseOrigin ( HttpServletRequest request) {
String ip= request. getRemoteAddr ( ) ;
return ip;
}
}