9.4 Spring Boot整合Spring Data Redis操作实体对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16855077/article/details/85000744

1.pom.xml

<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.cloudtech</groupId>
	<artifactId>01-springboot-hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.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>
	</properties>

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

		<!-- junit jar包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>

		<!-- mybatis启动器 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

		<!-- mysql数据库驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.9</version>
		</dependency>

		<!-- 增加thymeleaf坐标 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!-- 增加redis坐标 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

		<!--spring2.0集成redis所需common-pool2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
		</dependency>

		<!--fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.8</version>
		</dependency>

		<!-- 热部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>

		<!-- Spring Boot缓存支持启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>

		<!-- Ehcache坐标 -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>

		<!--通用Mapper -->
		<dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>2.0.3</version>
		</dependency>
		<!--pageHelper分页 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.5</version>
		</dependency>
	</dependencies>
</project>

2.application.yml

server:
  port: 8082

logging:
  level:
      com.cloudtech.dao: debug 
  
spring:
    redis:
      #数据库索引
      database: 0
      host: XXXXX
      port: 6379
      password: 123456
      jedis:
        pool:
          #最大连接数
          max-active: 8
          #最大阻塞等待时间(负数表示没限制)
          max-wait: -1
          #最大空闲
          max-idle: 8
          #最小空闲
          min-idle: 0
      #连接超时时间
      timeout: 10000
      
      
    datasource:
    #   数据源基本配置
        url: jdbc:mysql://XXX:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
        username: root
        password: root
        driver-class-name: com.mysql.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
    cache:  ##配置 ehcache缓存
    ehcache:
      config:  ehcache.xml  
      
#mybatis相关配置
mybatis:
  #当mybatis的xml文件和mapper接口不在相同包下时
  #需要用mapperLocations属性指定xml文件的路径。  
  #*是个通配符,代表所有的文件,**代表所有目录下
  mapper-locations: classpath*:/com/cloudtech/mapper/*.xml
  #指定bean所在包 
  #在mapper.xml中可以使用别名而不使用类的全路径名
  type-aliases-package: com.cloudtech.entity  
      
       
#通用mapper配置
mapper:
  identity: MYSQL   # 取主键的方式
  before: false      # 主键递增
  not-empty: true   # 按主键插入或更新时,是否判断字符串 != ''
  style: camelhumpandlowercase  # 实体类与表中字段的映射方式:驼峰转带下划线的小写格式
  wrap-keyword: '{0}'   # 自动配置关键字,配置后不需要使用 @Column 指定别名
  safe-delete: true   # 删除时必须设置查询条件
  safe-update: true   # 更新时必须设置查询条件
  use-java-type: true   # 是否映射Java基本数据类型
  mappers: tk.mybatis.mapper.common.Mapper
  
 
#pagehelper分页插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql           

3.  工具类

package com.cloudtech.config;
 
import java.util.concurrent.CountDownLatch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
/**
 * 
* @ClassName: RedisConfig  
* @Description:   
* @author wude  
* @date 2018年12月13日  
*
 */
@Configuration
@EnableCaching   //加入缓存
public class RedisConfig extends CachingConfigurerSupport {
	
	@Bean
	RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
			MessageListenerAdapter listenerAdapter) {
 
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
 
		return container;
	}
 
	@Bean
	MessageListenerAdapter listenerAdapter(Receiver receiver) {
		return new MessageListenerAdapter(receiver, "receiveMessage");
	}
 
	@Bean
	Receiver receiver(CountDownLatch latch) {
		return new Receiver(latch);
	}
 
	@Bean
	CountDownLatch latch() {
		return new CountDownLatch(1);
	}
 
	@Bean
	RedisTemplate<String, Object>  template(RedisConnectionFactory connectionFactory) {
		RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
		template.setConnectionFactory(connectionFactory);

		//为key设置序列化器
		template.setKeySerializer(new StringRedisSerializer());
		//为value设置序列化器
		template.setValueSerializer(new StringRedisSerializer());
		return template;
	}
	
	public class Receiver { 
		
 
		private CountDownLatch latch;
		
		@Autowired
		public Receiver(CountDownLatch latch) {
		    this.latch = latch;
		}
		
		public void receiveMessage(String message) {
		    latch.countDown();
		}
	}
	
	
}

role实体类

package com.cloudtech.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
 * 
* @ClassName: Role  
* @Description:  角色 
* @author wude  
* @date 2018年6月25日  
*
 */
public class Role implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Id
	@Column
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	/**
	 * @author wilson
	 *主键id
	 */
	private Integer id;
	/**
	 * @author wilson
	 *角色名称
	 */
    private String name;
    /**
     * @author wilson
     *角色描述
     */
    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description == null ? null : description.trim();
    }

	@Override
	public String toString() {
		return "Role [id=" + id + ", name=" + name + ", description=" + description + "]";
	}
}

4.单元测试

package com.cloudtech.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.cloudtech.App2;
import com.cloudtech.entity.Role;

/**
 * spring 测试类
 * @RunWith:启动器
 * SpringJUnit4ClassRunner  让junit和spring环境进行整合
 * @SpringBootTest  1.当前类为spring的测试类   2加载spring boot启动类,启动spring boots
 * 
* @ClassName: RoleTest  
* @Description:   
* @author wude  
* @date 2018年12月12日  
*
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App2.class})
public class RoleTest {
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 向redis中插入值
	 */
	@Test
	public void test2(){
		redisTemplate.opsForValue().append("shabao", "我是帅锅,哈哈哈哈哈");
	}
	
	/**
	 * 根据redis查询值
	 */
	@Test
	public void test3(){
		String string = (String) redisTemplate.opsForValue().get("shabao");
		System.out.println(string);
	}
	
	/**
	 * 插入user对象到redis中
	 */
	@Test
	public void test4(){
		Role role = new Role();
		role.setId(1);
		role.setName("test");
		role.setDescription("test123");
		
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.opsForValue().set("role", role);
	}
	
	/**
	 * 读取user对象
	 */
	@Test
	public void test5(){
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		Role role = (Role) redisTemplate.opsForValue().get("role");
		System.out.println(role.toString());
	}
}

运行test4,查询redis

数据显示乱码正常,为了测试数据写入是不是对的,我们可以运行test5方法,查看对应的值

5.json格式存储对象

单元测试类

/**
	 * 插入user对象到redis中(json方式)
	 */
	@Test
	public void test6(){
		Role role = new Role();
		role.setId(2);
		role.setName("测试");
		role.setDescription("测试123");
		
		redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(role.getClass()));
		redisTemplate.opsForValue().set("role", role);
	}
	
	/**
	 * 获取role数据(json方式)
	 */
	@Test
	public void test7(){
		redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Role.class));
		Role role = (Role) redisTemplate.opsForValue().get("role");
		System.out.println(role.toString());
	}

存放截图: 

 

注意:之前使用的是JdkSerializationRedisSerializer,现在使用的是Jackson2JsonRedisSerializer,后者比前者开销更小。 

猜你喜欢

转载自blog.csdn.net/qq_16855077/article/details/85000744