1、springboot配置文件application.yml
- #端口
- server:
- port: 8080
- #模板页面
- #注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改
- spring.thymeleaf.cache: false
- spring.thymeleaf.prefix: classpath:/templates/
- spring.thymeleaf.suffix: .html
- spring.thymeleaf.mode: LEGACYHTML5
- spring.thymeleaf.encoding: UTF-8
- spring.thymeleaf.content-type: text/html
- #spring-boot整合单机版redis redis作为缓存
- spring.redis.hostName: 192.168.1.103
- spring.redis.port: 6379
- spring.redis.password: xuan123456
- spring.redis.database: 2 #默认使用db0
- spring.redis.timeout: 0
- spring.redis.pool.max-active: 8
- spring.redis.pool.max-wait: -1
- spring.redis.pool.max-idle: 8
- spring.redis.pool.min-idle: 0
- ##数据源一
- #spring:
- # datasource:
- # driverClass: com.mysql.jdbc.Driver
- # url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
- # username: xuan
- # password: 123456
- #数据源二
- spring:
- datasource:
- url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
- username: xuan
- password: 123456
- # 使用druid数据源
- type: com.alibaba.druid.pool.DruidDataSource
- driver-class-name: com.mysql.cj.jdbc.Driver
- filters: stat
- maxActive: 20
- initialSize: 1
- maxWait: 60000
- minIdle: 1
- timeBetweenEvictionRunsMillis: 60000
- minEvictableIdleTimeMillis: 300000
- validationQuery: select 'x'
- testWhileIdle: true
- testOnBorrow: false
- testOnReturn: false
- poolPreparedStatements: true
- maxOpenPreparedStatements: 20
- #spring-boot整合mybatis
- mybatis:
- #config-location: classpath:/mapper/config/mybatisConfig.xml #可以注射掉,没用到该配置文件
- mapper-locations: classpath:/mapper/*Mapper.xml
- #type-aliases-package: com.xuan.entity
2、maven配置文件加入依赖:
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.xuan</groupId>
- <artifactId>myspringboot</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>myspringboot</name>
- <description>Demo project for Spring Boot</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.8.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- <mybatis.generator.version>1.3.2</mybatis.generator.version>
- <mysql.connector.java.version>6.0.6</mysql.connector.java.version>
- <!-- Used by MyBatis Generator to Generate Codes -->
- <!-- 运行命令: mvn mybatis-generator:generate -e -->
- <!--<classPathEntry.mysql.location>${basedir}/target/${project.artifactId}/WEB-INF/lib/mysql-connector-java-${mysql.connector.java.version}.jar</classPathEntry.mysql.location>-->
- <classPathEntry.mysql.location>/Users/chenqixuan/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar</classPathEntry.mysql.location>
- <javaModelGenerator.targetProject>${basedir}/src/main/java</javaModelGenerator.targetProject>
- <sqlMapGenerator.targetProject>${basedir}/src/main/resources</sqlMapGenerator.targetProject>
- <javaClientGenerator.targetProject>${basedir}/src/main/java</javaClientGenerator.targetProject>
- <mybatis.generator.configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</mybatis.generator.configurationFile>
- <mybatis.generator.overwrite>true</mybatis.generator.overwrite>
- </properties>
- <dependencies>
- <!--eureka server -->
- <!--<dependency>-->
- <!--<groupId>org.springframework.cloud</groupId>-->
- <!--<artifactId>spring-cloud-starter-eureka-server</artifactId>-->
- <!--</dependency>-->
- <!-- springboot整合redis -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
- <!-- springboot整合mybatis -->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.3.1</version>
- </dependency>
- <!-- mysql jdbc驱动 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>${mysql.connector.java.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jdbc</artifactId>
- </dependency>
- <!-- alibaba的druid数据库连接池 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.11</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- 模板页面 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- <dependency>
- <groupId>net.sourceforge.nekohtml</groupId>
- <artifactId>nekohtml</artifactId>
- <version>1.9.22</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <!--<dependencyManagement>-->
- <!--<dependencies>-->
- <!--<dependency>-->
- <!--<groupId>org.springframework.cloud</groupId>-->
- <!--<artifactId>spring-cloud-dependencies</artifactId>-->
- <!--<version>Dalston.RC1</version>-->
- <!--<type>pom</type>-->
- <!--<scope>import</scope>-->
- <!--</dependency>-->
- <!--</dependencies>-->
- <!--</dependencyManagement>-->
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- <!-- mybatis generator 自动生成代码插件 -->
- <plugin>
- <groupId>org.mybatis.generator</groupId>
- <artifactId>mybatis-generator-maven-plugin</artifactId>
- <version>${mybatis.generator.version}</version>
- </plugin>
- </plugins>
- </build>
- <repositories>
- <repository>
- <id>spring-milestones</id>
- <name>Spring Milestones</name>
- <url>https://repo.spring.io/milestone</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
- </repositories>
- </project>
3、springboot应用主入口开启缓存
- package com.xuan;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
- @SpringBootApplication
- @EnableCaching //开启缓存
- @EnableTransactionManagement // 开启事务管理
- @MapperScan("com.xuan.mapper") // 必须加这个,不加报错,如果不加,也可以在每个mapper上添加@Mapper注释,并且这里还要多填一个注释,那个我忘了,我一直用这个注解
- public class MyspringbootApplication {
- public static void main(String[] args) {
- SpringApplication.run(MyspringbootApplication.class, args);
- }
- }
4、到这一步就可以使用redis缓存,要结合更高级的redisTemplate去使用redis还需要添加一些配置类
springboot主入口开启缓存后,可以使用redis 测试注解使用:
- @GetMapping(value="/one/{id}")
- @Cacheable(value = "getOneVideo")
- public Video getOneVideo(@PathVariable Integer id){
- System.out.println("没redis缓存");
- return videoMapper.selectByPrimaryKey(id);
- }
5、增加集成redistemplate配置(读取springboot配置文件的值的时候,名称注意一一对应,否则会读取不到)
- package com.xuan.config;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import redis.clients.jedis.JedisPoolConfig;
- /**
- * Created by chenqixuan on 17/10/25.
- * 集成RedisTemplate
- */
- @Configuration
- @EnableAutoConfiguration
- public class RedisConfig {
- private static Logger logger = Logger.getLogger(RedisConfig.class);
- //获取springboot配置文件的值 (get的时候获取)
- @Value("${spring.redis.hostName}")
- private String host;
- @Value("${spring.redis.password}")
- private String password;
- /**
- * @Bean 和 @ConfigurationProperties
- * 该功能在官方文档是没有提到的,我们可以把@ConfigurationProperties和@Bean和在一起使用。
- * 举个例子,我们需要用@Bean配置一个Config对象,Config对象有a,b,c成员变量需要配置,
- * 那么我们只要在yml或properties中定义了a=1,b=2,c=3,
- * 然后通过@ConfigurationProperties就能把值注入进Config对象中
- * @return
- */
- @Bean
- @ConfigurationProperties(prefix = "spring.redis.pool")
- public JedisPoolConfig getRedisConfig() {
- JedisPoolConfig config = new JedisPoolConfig();
- return config;
- }
- @Bean
- @ConfigurationProperties(prefix = "spring.redis")
- public JedisConnectionFactory getConnectionFactory() {
- JedisConnectionFactory factory = new JedisConnectionFactory();
- factory.setUsePool(true);
- JedisPoolConfig config = getRedisConfig();
- factory.setPoolConfig(config);
- logger.info("JedisConnectionFactory bean init success.");
- return factory;
- }
- @Bean
- public RedisTemplate<?, ?> getRedisTemplate() {
- JedisConnectionFactory factory = getConnectionFactory();
- logger.info(this.host+","+factory.getHostName()+","+factory.getDatabase());
- logger.info(this.password+","+factory.getPassword());
- logger.info(factory.getPoolConfig().getMaxIdle());
- // factory.setHostName(this.host);
- // factory.setPassword(this.password);
- RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory());
- return template;
- }
- }
6、基于redistemplate的工具类
- package com.xuan.services.impl;
- import com.xuan.services.RedisService;
- import com.xuan.utils.JSONUtil;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.dao.DataAccessException;
- import org.springframework.data.redis.connection.RedisConnection;
- import org.springframework.data.redis.core.RedisCallback;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.RedisSerializer;
- import org.springframework.stereotype.Service;
- import javax.annotation.Resource;
- import java.util.List;
- import java.util.concurrent.TimeUnit;
- /**
- * Created by chenqixuan on 17/10/25.
- *
- */
- @Service
- public class RedisServiceImpl implements RedisService {
- @Resource
- private RedisTemplate<String, ?> redisTemplate;
- @Override
- public boolean set(final String key, final String value) {
- boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
- @Override
- public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
- RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
- connection.set(serializer.serialize(key), serializer.serialize(value));
- return true;
- }
- });
- return result;
- }
- @Override
- public String get(final String key){
- String result = redisTemplate.execute(new RedisCallback<String>() {
- @Override
- public String doInRedis(RedisConnection connection) throws DataAccessException {
- RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
- byte[] value = connection.get(serializer.serialize(key));
- return serializer.deserialize(value);
- }
- });
- return result;
- }
- @Override
- public boolean expire(final String key, long expire) {
- return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
- }
- @Override
- public <T> boolean setList(String key, List<T> list) {
- String value = JSONUtil.toJson(list);
- return set(key,value);
- }
- @Override
- public <T> List<T> getList(String key, Class<T> clz) {
- String json = get(key);
- if(json!=null){
- List<T> list = JSONUtil.toList(json, clz);
- return list;
- }
- return null;
- }
- @Override
- public long lpush(final String key, Object obj) {
- final String value = JSONUtil.toJson(obj);
- long result = redisTemplate.execute(new RedisCallback<Long>() {
- @Override
- public Long doInRedis(RedisConnection connection) throws DataAccessException {
- RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
- long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
- return count;
- }
- });
- return result;
- }
- @Override
- public long rpush(final String key, Object obj) {
- final String value = JSONUtil.toJson(obj);
- long result = redisTemplate.execute(new RedisCallback<Long>() {
- @Override
- public Long doInRedis(RedisConnection connection) throws DataAccessException {
- RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
- long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
- return count;
- }
- });
- return result;
- }
- @Override
- public String lpop(final String key) {
- String result = redisTemplate.execute(new RedisCallback<String>() {
- @Override
- public String doInRedis(RedisConnection connection) throws DataAccessException {
- RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
- byte[] res = connection.lPop(serializer.serialize(key));
- return serializer.deserialize(res);
- }
- });
- return result;
- }
- }
7、Json工具类:利用了gson依赖
- package com.xuan.utils;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import com.google.gson.Gson;
- import com.google.gson.JsonArray;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import com.google.gson.reflect.TypeToken;
- /**
- *
- * Created by chenqixuan on 17/10/25.
- * @desc json util
- */
- public class JSONUtil {
- private static Gson gson = null;
- static{
- gson = new Gson();//todo yyyy-MM-dd HH:mm:ss
- }
- public static synchronized Gson newInstance(){
- if(gson == null){
- gson = new Gson();
- }
- return gson;
- }
- public static String toJson(Object obj){
- return gson.toJson(obj);
- }
- public static <T> T toBean(String json,Class<T> clz){
- return gson.fromJson(json, clz);
- }
- public static <T> Map<String, T> toMap(String json,Class<T> clz){
- Map<String, JsonObject> map = gson.fromJson(json, new TypeToken<Map<String,JsonObject>>(){}.getType());
- Map<String, T> result = new HashMap<>();
- for(String key:map.keySet()){
- result.put(key,gson.fromJson(map.get(key),clz) );
- }
- return result;
- }
- public static Map<String, Object> toMap(String json){
- Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String,Object>>(){}.getType());
- return map;
- }
- public static <T> List<T> toList(String json,Class<T> clz){
- JsonArray array = new JsonParser().parse(json).getAsJsonArray();
- List<T> list = new ArrayList<>();
- for(final JsonElement elem : array){
- list.add(gson.fromJson(elem, clz));
- }
- return list;
- }
- public static void main(String[] args) {
- }
- }
8、使用:
- package com.xuan.controller;
- import com.xuan.config.RedisProperties;
- import com.xuan.entity.Video;
- import com.xuan.entity.VideoExample;
- import com.xuan.mapper.VideoMapper;
- import com.xuan.services.RedisService;
- import com.xuan.services.VideoService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import java.util.List;
- /**
- * Created by chenqixuan on 17/10/25.
- */
- @RestController
- @RequestMapping("/video")
- public class VideoController {
- @Autowired
- private VideoMapper videoMapper;
- @Autowired
- private VideoService videoService;
- @Autowired
- private RedisService redisService;
- @GetMapping(value="/redis/{id}")
- public List<Video> getAllVideo(@PathVariable String id){
- redisService.set(id,id);
- System.out.println(redisService.get(id));
- VideoExample example = new VideoExample();
- return videoMapper.selectByExample(example);
- }
- @GetMapping(value="/all")
- public List<Video> getAllVideo(){
- redisService.set("key2","9999");
- VideoExample example = new VideoExample();
- return videoMapper.selectByExample(example);
- }
- @GetMapping(value="/one/{id}")
- @Cacheable(value = "getOneVideo")
- public Video getOneVideo(@PathVariable Integer id){
- System.out.println("没redis缓存");
- return videoMapper.selectByPrimaryKey(id);
- }
- /**
- * 事务验证
- * @return
- */
- @GetMapping(value="/add")
- public String addVideo(){
- try {
- videoService.addVideo();
- return "Transactional YES";
- } catch (Exception e) {
- e.printStackTrace();
- return "Transactional NO";
- }
- }
- }