Part One 创建工程及前期准备工作
开发工具使用idea,创建springboot项目 [1.5.13版本]
选择pom配置
pom文件如下所示
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- **********************Druid数据源********************** --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <!-- **********************JSON********************** --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
yml配置文件
# 数据源 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/db_test?characterEncoding=utf8&useSSL=true username: root password: root #最大活跃数 maxActive: 20 #初始化数量 initialSize: 5 #最大连接等待超时时间 maxWait: 60000 #打开PSCache,并且指定每个连接PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 #通过connectionProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #基本属性 minIdle: 5 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false #合并多个DruidDataSource的监控数据 useGlobalDataSourceStat: true #配置监控统计拦截的filters filters: stat,wall,slf4j # 配置redis数据库连接 redis: host: 10.0.0.10 #linux控制台输入ifconfig命令 查看 port: 6379 pool: max-idle: 8 min-idle: 0 max-active: 8 max-wait: -1 database: 0 #默认是索引为0的数据库
相关配置类
1)Druid配置类@Configuration public class DruidDataSourceConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ System.err.println("数据源配置成功......."); return new DruidDataSource(); } /** * 配置Druid的监控 * 1、配置一个管理后台的Servlet * @return */ @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); Map<String,String> initParams=new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","admin"); initParams.put("allow","");//默认就是允许所有访问 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } /** * 2、配置一个web监控的filter * @return */ @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean=new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*,*.html"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
2)mybatis配置类
@Configuration public class MyBatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer() { @Override public void customize(org.apache.ibatis.session.Configuration configuration) { //-自动使用驼峰命名属性映射字段 userId user_id configuration.setMapUnderscoreToCamelCase(true); //使用列别名替换列名 select user as User configuration.setUseColumnLabel(true); } }; } }
3)redis配置类
@Configuration @EnableCaching //开启缓存 public class RedisConfig { /** * 采用RedisCacheManager作为缓存管理器 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisTemplate redisTemplate){ return new RedisCacheManager(redisTemplate); } }
数据库
entity层
//需要序列化
public class Dept implements Serializable{
private Integer deptNo;
private String deptName;
public Integer getDeptNo() {
return deptNo;
}
public void setDeptNo(Integer deptNo) {
this.deptNo = deptNo;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Dept{" +
"deptNo=" + deptNo +
", deptName='" + deptName + '\'' +
'}';
}
}
Part Two linux中redis配置更改
永久关闭防火墙[不然会被拦截访问]
chkconfig iptables off
报这个错误
redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled,
no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface.
If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command ’
CONFIG SET protected-mode no’ from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not
publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode
by editing the Redis configuration file, and setting the protected mode option to ‘no’, and then restarting the server. 3) If you started the server
manually just for testing, restart it with the ‘–protected-mode no’ option. 4) Setup a bind address or an authentication password. NOTE: You only need
to do one of the above things in order for the server to start accepting connections from the outside.
解决方法:vim打开redis.conf 更改protected-mode属性 yes改为no
出现这样的错误是因为你启动redis服务时开启了保护模式
保护模式,默认开启。要是配置里没有指定bind和密码。开启该参数后,redis只会本地进行访问,拒绝外部访问。要是开启了密码和bind,可以开启。否则最好关闭,设置为no。报这个错误
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
redis拒绝我们的连接是因为redis.conf 文件中默认打开bind 127.0.0.1,打开这个设置后redis 只接收来自于该 IP 地址的请求,如果不进行设置,那么将处理所有请求。
Part 3 执行代码
只介绍service层
@CacheConfig(cacheNames = "deptCache")
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
@Cacheable
@Override
public List<Dept> queryDeptById() {
return deptMapper.selectDeptById();
}
}
可能用到常用注解:
@CacheConfig:该注解是用来开启声明的类参与缓存,如果方法内的@Cacheable注解没有添加key值,那么会自动使用cahceNames配置参数并且追加方法名。
@Cacheable:配置方法的缓存参数,可自定义缓存的key以及value。先查看缓存是否有数据,有则不执行方法;否则执行方法,在存入缓存区
@CachePut:先执行方法,然后把返回值保存或更新到缓存中
@CacheEvict(key=”#p0”) : 删除缓存名称为deptCache,key等于指定的对应的缓存 //#p0表示第一个参数
@CacheEvict(allEntries = true) :清空缓存名称为deptCache(看类名上的注解)下的所有缓存 如果数据失败了,缓存时不会清除的