天天看点

(仿牛客社区项目)Java开发笔记8.2:项目监控项目监控1.添加依赖2.修改配置文件3.actuator包4.config包5.功能测试

文章目录

  • 项目监控
  • 1.添加依赖
  • 2.修改配置文件
  • 3.actuator包
  • 4.config包
  • 5.功能测试

项目监控

(仿牛客社区项目)Java开发笔记8.2:项目监控项目监控1.添加依赖2.修改配置文件3.actuator包4.config包5.功能测试

1.添加依赖

导入spring-boot-starter-actuator依赖包。

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
           

2.修改配置文件

修改配置文件,配置actuator信息。

#actuator
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=info,caches
           

3.actuator包

自定义端点:新建actuator包,创建DatabaseEndpoint类。

package com.gerrard.community.actuator;

import com.gerrard.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.stereotype.Component;

import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


@Component
@Endpoint(id="database")
public class DatabaseEndpoint {

    private static final Logger logger= LoggerFactory.getLogger(DatabaseEndpoint.class);

    @Autowired
    private DataSource dataSource;

    @ReadOperation //只能通过get请求访问
    public String checkConnection(){

        try (
            Connection conn=dataSource.getConnection();
            ){
            return CommunityUtil.getJSONString(0,"获取连接成功!");
        } catch (SQLException e) {
            logger.error("获取连接失败:"+e.getMessage());
            return CommunityUtil.getJSONString(1,"获取连接失败!");
        }

    }

}
           

4.config包

Config包:在SecurityConfig类中配置相关权限。

package com.gerrard.community.config;

import com.gerrard.community.util.CommunityConstant;
import com.gerrard.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 授权
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(
                        AUTHORITY_USER,
                        AUTHORITY_ADMIN,
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/delete",
                        "/data/**",
                        "/actuator/**"  //项目监控
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
                .anyRequest().permitAll()
                .and().csrf().disable();

        // 权限不够时的处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    // 没有登录
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你还没有登录哦!"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    // 权限不足
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限!"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        // Security底层默认会拦截/logout请求,进行退出处理.
        // 覆盖它默认的逻辑,才能执行我们自己的退出代码.


        //认证,认证的逻辑用自己的代码,哪些地方需要认证配置自己用api配一下,认证成功/失败用api配一下
        //判断是否登录交给security,用的是securitycontext?
        http.logout().logoutUrl("/securitylogout");
    }

}
           

5.功能测试

登录管理员账号。

访问health端点:

(仿牛客社区项目)Java开发笔记8.2:项目监控项目监控1.添加依赖2.修改配置文件3.actuator包4.config包5.功能测试

访问自定义的database端点。

(仿牛客社区项目)Java开发笔记8.2:项目监控项目监控1.添加依赖2.修改配置文件3.actuator包4.config包5.功能测试