SpringBoot分布式管理,添加日志记录,注解配置与EhCache使用

    首先看下项目结构:



SpringBoot分布式管理,添加日志记录,注解配置与EhCache使用_第1张图片

首先看下pom.xml配置的jar包:


  4.0.0
  com
  SpringBootTest
  0.0.1-SNAPSHOT
  war
  
  
  
  
		org.springframework.boot
		spring-boot-starter-parent
		1.3.3.RELEASE
		 
  
  
  
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        
        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.1.1
	    

		
		
			mysql
			mysql-connector-java
		
		
		
		
			org.springframework.boot
			spring-boot-starter-jta-atomikos
		
		
		
		
			org.springframework.boot
			spring-boot-starter-aop
	    
	    
	    
	    
			org.springframework.boot
			spring-boot-starter-cache
		
	    
		
		
  
  
  
  
  
  	
  		
  			maven-war-plugin
  			
  				2.5
  			
  		
  	
  
 

application.properties里面配置数据库的链接信息
spring.mvc.view.prefix=/WEB-INF/jsp/

spring.mvc.view.suffix=.jsp


# Mysql 1
mysql.datasource.test.url = jdbc:mysql://192.168.10.205:3306/test1
mysql.datasource.test.username = root
mysql.datasource.test.password = root

mysql.datasource.test.minPoolSize = 3
mysql.datasource.test.maxPoolSize = 25
mysql.datasource.test.maxLifetime = 20000
mysql.datasource.test.borrowConnectionTimeout = 30
mysql.datasource.test.loginTimeout = 30
mysql.datasource.test.maintenanceInterval = 60
mysql.datasource.test.maxIdleTime = 60


# Mysql 2
mysql.datasource.test2.url =jdbc:mysql://192.168.10.205:3306/test2
mysql.datasource.test2.username =root
mysql.datasource.test2.password =root

mysql.datasource.test2.minPoolSize = 3
mysql.datasource.test2.maxPoolSize = 25
mysql.datasource.test2.maxLifetime = 20000
mysql.datasource.test2.borrowConnectionTimeout = 30
mysql.datasource.test2.loginTimeout = 30
mysql.datasource.test2.maintenanceInterval = 60
mysql.datasource.test2.maxIdleTime = 60
DBConfig1,这个文件的作用设计把数据库的配置信息全部拿过来用 atomikos进行分布式管理:
package com.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
/**
 * 
*类描述:读取application.properties数据源1的配置信息,如用户名,密码等
*@author: blank
*@date: 日期:2018-1-24 时间:上午8:56:59
*
 */
@ConfigurationProperties(prefix = "mysql.datasource.test")
public class DBConfig1 {

	private String url;
	private String username;
	private String password;
	private int minPoolSize;
	private int maxPoolSize;
	private int maxLifetime;
	private int borrowConnectionTimeout;
	private int loginTimeout;
	private int maintenanceInterval;
	private int maxIdleTime;
	private String testQuery;
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getMinPoolSize() {
		return minPoolSize;
	}
	public void setMinPoolSize(int minPoolSize) {
		this.minPoolSize = minPoolSize;
	}
	public int getMaxPoolSize() {
		return maxPoolSize;
	}
	public void setMaxPoolSize(int maxPoolSize) {
		this.maxPoolSize = maxPoolSize;
	}
	public int getMaxLifetime() {
		return maxLifetime;
	}
	public void setMaxLifetime(int maxLifetime) {
		this.maxLifetime = maxLifetime;
	}
	public int getBorrowConnectionTimeout() {
		return borrowConnectionTimeout;
	}
	public void setBorrowConnectionTimeout(int borrowConnectionTimeout) {
		this.borrowConnectionTimeout = borrowConnectionTimeout;
	}
	public int getLoginTimeout() {
		return loginTimeout;
	}
	public void setLoginTimeout(int loginTimeout) {
		this.loginTimeout = loginTimeout;
	}
	public int getMaintenanceInterval() {
		return maintenanceInterval;
	}
	public void setMaintenanceInterval(int maintenanceInterval) {
		this.maintenanceInterval = maintenanceInterval;
	}
	public int getMaxIdleTime() {
		return maxIdleTime;
	}
	public void setMaxIdleTime(int maxIdleTime) {
		this.maxIdleTime = maxIdleTime;
	}
	public String getTestQuery() {
		return testQuery;
	}
	public void setTestQuery(String testQuery) {
		this.testQuery = testQuery;
	}
	
}

WebLogAspect:这里面是定义日志的内容:

package com.controller;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect//定义一个切面
@Component
public class WebLogAspect {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Pointcut("execution(public * com.controller..*.*(..))")//插入的地方
	public void webLog() {
	}
	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		// 接收到请求,记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		logger.info("URL : " + request.getRequestURL().toString());
		logger.info("HTTP_METHOD : " + request.getMethod());
		logger.info("IP : " + request.getRemoteAddr());
		Enumeration enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String name = (String) enu.nextElement();
			logger.info("name:{},value:{}", name, request.getParameter(name));
		}
	}
	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void doAfterReturning(Object ret) throws Throwable {
		// 处理完请求,返回内容
		logger.info("RESPONSE : " + ret);
	}

}
IndexController:主类中里面应注解对各个方法进行调用:

package com.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.test01.mapper.UserMapper01;
import com.test02.mapper.UserMapper02;

@RestController
public class IndexController {

	//使用日志
	private static Logger log=Logger.getLogger(IndexController.class);
	
	@Autowired
	private CacheManager cacheManager;
	
	//自定义数值
//	@Value("${name}")
//	private String name;

	
	@Autowired
	private UserMapper01 userMapper1;

	@Autowired
	private UserMapper02 userMapper2;

	@RequestMapping("/adduser")
	public String adduser(String name, Integer age) {
		userMapper1.insertUsers("大肠", 22);
		userMapper2.insertUsers("阿干", 33);
		return "success";
	}
	//写日志
	@RequestMapping("/log")
	public String log(){
		log.info("test log");
		return "success";
	}
	@ResponseBody
	@RequestMapping("/addUserName")
	public String addUserName(String name){
		return "success";
	}
	//查询语句
	@ResponseBody
	@RequestMapping("/selectusers")
	public String getUsers(Integer id){
		return userMapper1.findUsersByid(id).toString();
		
	}
	//清除缓存
	@ResponseBody
	@RequestMapping("/remoKey")
	public String remoKey() {
		cacheManager.getCache("baseCache").clear();
		return "success";
	}
	//自定义数值
//	@ResponseBody
//	@RequestMapping("/getValue")
//	public String getValue() {
//		return name;
//	}

}
TestMyBatisConfig1,配置数据源信息(把数据源信息交给Atomikos来处理):

package com.datasources;

import java.sql.SQLException;

import javax.sql.DataSource;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.config.DBConfig1;
import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;



@Configuration
//basePackages 最好分开配置 如果放在同一个文件夹可能会报错
@MapperScan(basePackages = "com.test01", sqlSessionTemplateRef = "testSqlSessionTemplate")

public class TestMyBatisConfig1 {
	// 配置数据源
		@Primary
		@Bean(name = "testDataSource")
		public DataSource testDataSource(DBConfig1 testConfig) throws SQLException {
			MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
			mysqlXaDataSource.setUrl(testConfig.getUrl());
			mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
			mysqlXaDataSource.setPassword(testConfig.getPassword());
			mysqlXaDataSource.setUser(testConfig.getUsername());
			mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

			AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
			xaDataSource.setXaDataSource(mysqlXaDataSource);
			xaDataSource.setUniqueResourceName("testDataSource");

			xaDataSource.setMinPoolSize(testConfig.getMinPoolSize());
			xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize());
			xaDataSource.setMaxLifetime(testConfig.getMaxLifetime());
			xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout());
			xaDataSource.setLoginTimeout(testConfig.getLoginTimeout());
			xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval());
			xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime());
			xaDataSource.setTestQuery(testConfig.getTestQuery());
			return xaDataSource;
		}

		@Bean(name = "testSqlSessionFactory")
		public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource)
				throws Exception {
			SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
			bean.setDataSource(dataSource);
			return bean.getObject();
		}

		@Bean(name = "testSqlSessionTemplate")
		public SqlSessionTemplate testSqlSessionTemplate(
				@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
			return new SqlSessionTemplate(sqlSessionFactory);
		}
	}
Users实体:
package com.model;

public class Users {
	private int id;
	private String name;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Users [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}
UserMapper01,对数据库1进行操作

package com.test01.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;

import com.model.Users;

@CacheConfig(cacheNames = "baseCache")
public interface UserMapper01 {
	
	@Select("select * from users where id=#{id}")
	@Cacheable
	Users findUsersByid(@Param("id")Integer id);
	
//	@Select("select * from users")
//	@Cacheable
//	Users selectallUsers();
	
	@Insert("insert into users values(null,#{name},#{age});")
	int insertUsers(@Param("name")String name,@Param("age")Integer age);
}
service层:
package com.test01.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.test01.mapper.UserMapper01;

@Service
public class UserService01 {
	
	@Autowired
	private UserMapper01 userMapper1;
	
	//事务回滚,如果这部分出错,将会回滚
	@Transactional
	public int addUser(String name,Integer age){
		return userMapper1.insertUsers(name, age);
	}
}
log4j.properties这里是配置日志:

#log4j.rootLogger=CONSOLE,info,error,DEBUG
log4j.rootLogger=info,error,CONSOLE,DEBUG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender     
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout     
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n     
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout     
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n  
log4j.appender.info.datePattern='.'yyyy-MM-dd
log4j.appender.info.Threshold = info   
log4j.appender.info.append=true   
#log4j.appender.info.File=/home/admin/pms-api-services/logs/info/api_services_info
log4j.appender.info.File=/Users/dddd/Documents/testspace/pms-api-services/logs/info/api_services_info
log4j.logger.error=error  
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout     
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n  
log4j.appender.error.datePattern='.'yyyy-MM-dd
log4j.appender.error.Threshold = error   
log4j.appender.error.append=true   
#log4j.appender.error.File=/home/admin/pms-api-services/logs/error/api_services_error
log4j.appender.error.File=/Users/dddd/Documents/testspace/pms-api-services/logs/error/api_services_error
log4j.logger.DEBUG=DEBUG
log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout     
log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n  
log4j.appender.DEBUG.datePattern='.'yyyy-MM-dd
log4j.appender.DEBUG.Threshold = DEBUG   
log4j.appender.DEBUG.append=true   
#log4j.appender.DEBUG.File=/home/admin/pms-api-services/logs/debug/api_services_debug
log4j.appender.DEBUG.File=/Users/dddd/Documents/testspace/pms-api-services/logs/debug/api_services_debug
ehcache.xml:配置缓存



	

	
	

	


最后来到主程序:

APP:

package com.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;

import com.config.DBConfig1;
import com.config.DBConfig2;

//有多个项目的时候,要加入这个注解,用来扫描包,扫描service层和dao层
@ComponentScan(basePackages={"com.controller","com.config","com.datasources","com.test01","com.test02"})
//开启缓存注解
@EnableCaching
//开启定时任务注解
//@EnableScheduling
//只能使用者一个注解
@EnableAutoConfiguration
//开启读取这两个配置文件
@EnableConfigurationProperties(value = { DBConfig1.class, DBConfig2.class })
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class,args);
	}

}
最后启动。















你可能感兴趣的:(SpringBoot)