赞
踩
pom.xml
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!--mybatis-plus代码生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </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> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.8</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- lettuce pool 缓存连接池--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.yml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.6.4</version> </plugin> </plugins> </build>
RedisConfig
@Configuration @EnableCaching public class RedisConfig { /** * 往容器中添加RedisTemplate对象,设置序列化方式 * * @param redisConnectionFactory * @return * @throws UnknownHostException */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<String, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(valueSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(valueSerializer()); template.afterPropertiesSet(); return template; } /** * 往容器中添加RedisCacheManager容器,并设置序列化方式 * * @param redisConnectionFactory * @return */ @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer())); redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())); return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration); } /** * 使用Jackson序列化器 * * @return */ private RedisSerializer<Object> valueSerializer() { Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(objectMapper); return serializer; } }
AutoCodeGenerator
public class AutoCodeGenerator { private static String author = "hao"; private static String first_level_package_name = "com"; private static String second_level_package_name = "hao"; private static String table_to_entity = "all"; private static String url = "jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true"; private static String username = "root"; private static String password = "123456"; public static void main(String[] args) throws IOException { // 数据库配置 DataSourceConfig.Builder dataSourceConfigBuilder = new DataSourceConfig .Builder(url, username, password); FastAutoGenerator.create(dataSourceConfigBuilder) // 全局配置 .globalConfig((scanner, builder) -> { builder.author(author) // 覆盖已生成文件 .fileOverride() // 指定输出目录 .outputDir(System.getProperty("user.dir") + "/src/main/java/") // 禁止打开输出目录 .disableOpenDir() // 时间策略 .dateType(DateType.TIME_PACK) // 类注释日期的格式 .commentDate("yyyy-MM-dd") .build(); }) // 包配置 .packageConfig((scanner, builder) -> { // 父包名 builder.parent(first_level_package_name) // 模块名 .moduleName(second_level_package_name) // Entity 包名 .entity("entity") // Service 包名 .service("service") // Controller 包名 .controller("controller") // Mapper 包名 .mapper("mapper") // MapperXML 包名 .xml("mapper") // 路径配置信息 .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "/src/main/resources/mapper")); }) //策略配置 .strategyConfig((scanner, builder) -> { // 增加表匹配(内存过滤), include 与 exclude 只能配置一项 builder.addInclude(getTables(table_to_entity)) // 增加表排除匹配(内存过滤), include 与 exclude 只能配置一项 // .addExclude(scanner.apply("请输入要忽略的表名,多个英文逗号分隔?")) // 增加过滤表后缀 .addTableSuffix("") // 增加过滤表前缀 .addTablePrefix("") // service 策略配置 .serviceBuilder() // 格式化文件名称 .formatServiceFileName("%sService") .formatServiceImplFileName("%sServiceImpl") // 实体策略配置 .entityBuilder() //AR模式 .enableActiveRecord() // 开启生成实体时生成字段注解 .enableTableFieldAnnotation() // controller 策略配置 .controllerBuilder() .formatFileName("%sController") // 开启生成@RestController 控制器 // .enableRestStyle() // mapper 策略配置 .mapperBuilder() // 设置父类 .superClass(BaseMapper.class) .formatMapperFileName("%sMapper") .enableMapperAnnotation() .formatXmlFileName("%sMapper"); }) .execute(); } /** * 处理 all 情况 * 要生成的表名,以英文逗号分隔多个表格名(所有表填all) * * @param tables * @return */ protected static List<String> getTables(String tables) { return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(",")); } }
application.yml
server: port: 8080 encoding: charset: UTF-8 spring: mvc: #视图解析器 view: prefix: / suffix: .jsp datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource redis: host: 127.0.0.1 port: 6379 password: 123456 jedis: pool: max-active: 8 max-wait: -1ms max-idle: 500 min-idle: 0 lettuce: shutdown-timeout: 0ms mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.hao.entity configuration: #开启驼峰映射 map-underscore-to-camel-case: true # sql日志的打印 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #showSql logging: level: com.hao.mapper: debug
在查询类的方法前面注解@Cacheable(value = " ",key = " ")
@Resource private UserInfoMapper mapper; @Resource private UserInfoService service; @Resource private RedisTemplate<String, String> redisTemplate; @Test void testMysql() { List<UserInfo> userInfos = mapper.selectList(null); for (UserInfo userInfo : userInfos) { System.out.println(userInfo); } } @Test void testRedis() { redisTemplate.opsForValue().set("name", "hao"); System.out.println(redisTemplate.opsForValue().get("name")); } @Test void testCacheable() { System.out.println("===========第一次查询==========="); UserInfo userById = service.findUserById(3); System.out.println(userById); System.out.println("===========第二次查询==========="); UserInfo userById2 = service.findUserById(3); System.out.println(userById2); }
测试数据库连接
测试redis连接
测试@cacheable
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。