EE颠覆者第八章3,MongoDB和Redis

nosql

是对不使用关系作为数据管理的数据库系统的统称。

不使用sql语言作为查询语言,数据存储也不是固定的表,字段。

文档存储型 mongoDB

图标关系存储型 neo4j

键值对存储型 redis

mongoDB

使用面向对象的思想,每一条数据记录都是文档的对象

Spring Data MongoDB

  1. object/Document映射注解的支持

jpa Object/Relation映射的注解(@Entiry @Id)

而 Spring Data MongoDB也提供了如下

@Document 映射领域对象 与 mongoDB 的一个文档

@ID 映射当前属性的ID

@DbRef 当前属性,将参考其他的文档

@Field 为文档的属性定义名称

@Version 将当前属性作为版本

  1. MongoTemplate

我们为MongoClient 以及 MongoDbFactory

    @Bean//1,先配置 mongoClient
    public MongoClient client() throws UnknownHostException {
        MongoClient client=new MongoClient(new ServerAddress("127.0.0.1",27017));
        return client;
    }

    @Bean//2,在配置mongoDb工厂
    public MongoDbFactory mongoDbFactory() throws Exception{
        String database = new MongoClientURI("mongodb://localhost/test").getDatabase();
        return new SimpleMongoDbFactory(client(),database);
    }

    @Bean//3,在配置mongo操作类
    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory){
        return new MongoTemplate(mongoDbFactory);
    }

  1. Repository支持和 开启mongo
 extends MongoRepository<Person, String> {
	


@Configuration
@EnableMongoRepositories  //只需要引入依赖即可


配置文件

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      uri: mongodb://localhost/test
      database: test
      authentication-database: test
      grid-fs-database: test
      username: abc
      password: abc
      repositories:
        enabled: true
      field-naming-strategy: abc

启动

 docker run -d -p 27017:27017 mongo

https://www.robomongo.org/ 查看软件。用robot 3T

pom

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

领域模型

@Document //1 注册映射领域模型 和 mongoDB的文档
public class Person {
	@Id//文档的Id
	private String id;
	private String name;
	private Integer age;
    
	@Field("locs")//工作过的地点。在文档的名称为locs,locations将以数组形式存在当前数据记录中
	private Collection<Location> locations =  new LinkedHashSet<Location>();
	

	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
}//get set



public class Location {
	
	private String place;
	
	private String year;
}

数据访问

public interface PersonRepository extends MongoRepository<Person, String> {
	
	 Person findByName(String name);//方法名查询
	
	 @Query("{'age': ?0}") //@Query查询
	 List<Person> withQueryFindByAge(Integer age);

}

控制器

@RestController
public class DataController {
	
	@Autowired
	PersonRepository personRepository;
	
	@RequestMapping("/save")
	public Person save(){
		Person  p = new Person("wyf",32);
		Collection<Location> locations =  new LinkedHashSet<Location>();
		Location loc1 = new Location("上海","2009");
		Location loc2 = new Location("合肥","2010");
		locations.add(loc1);
		locations.add(loc2);

		p.setLocations(locations);
		
		return personRepository.save(p);
	}
	
	@RequestMapping("/q1")
	public Person q1(String name){
		return personRepository.findByName(name);
	}
	
	@RequestMapping("/q2")
	public List<Person> q2(Integer age){
		return personRepository.withQueryFindByAge(age);
	}

}
http://localhost:8080/save
http://localhost:8080/q1?name=wyf



redis

基于键值的开源内存数据存储,也可以做数据缓存

Spring Data Redis

Spring Data Jpa 提供了 ConnectionFactory和 RedisTemplate

Spring Data Redis 提供了 如下: ConnectionFactory:

  1. JedisConnectionFactory
  2. JredisConnectionFactory
  3. LettuceConnectionFactory
  4. SrqConnectionFactory # 使用 Spullara/redis-protocol ,作为redis客户端

配置

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        return new JedisConnectionFactory();
    }
    public RedisTemplate<Object, Object> redisTemplate(){
        RedisTemplate<Object,Object> template=new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        return template;
    }

提供了:

RedisTemplate 和 StringRedisTemplate(只是针对键值都是字符型的数据进行操作)

方法 说明
opsForValue() 只有简单属性的数据
opsForList() 含有list的数据
opsForSet() 含有set的数据
opsForZSet() 含有ZSet(有序set)的数据
opsForHash() 含有hash的数据

定义Serializer

我们的键值都是通过Spring提供的 Serializer 序列化到数据库的。

RedisTemplate 默认使用: Jdk Serialization Redis Serializer

StringRedisTemplate 默认使用:StringRedisSerializer

此外还有:

GenericToStringSerializer

Jackson2JsonRedisSerializer

JacksonJsonRedisSerializer

OxmSerializer

默认配置

RedisAutoConfiguration为我们默认配置了

JedisConnectionFactory

RedisTemplate

StringRedisTemplate

配置文件用 Spring.redis开头

spring:
  redis:
    database: 0
    host: 192.168.31.183
    password:
    port: 6379
    pool:
      max-idle: 8
      min-idle: 0
      max-active: 8
      max-wait: -1
    sentinel:
      master:
      nodes:
    timeout: 0
docker run -d -p 6379:6379 redis

redis实战

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

领域模型

public class Person implements Serializable{ //序列化

	private static final long serialVersionUID = 1L;//序列化要用的版本号
	
	private String id;
	private String name;
	private Integer age;
	
	public Person() {//必须有空构造(jackson需要)
		super();
	}
	
	public Person(String id,String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
}

dao数据访问

@Repository
public class PersonDao {
	
	@Autowired
	StringRedisTemplate stringRedisTemplate; //1 自动注入,已经默认配置好
	
	@Resource(name="stringRedisTemplate")
	ValueOperations<String,String> valOpsStr; //3 注入基于字符串的简单属性操作的方法
	
	
	@Autowired
	RedisTemplate<Object, Object> redisTemplate; //2 自动注入,已经默认配置好
	
	@Resource(name="redisTemplate")
	ValueOperations<Object, Object> valOps; //4 注入基于对象的简单属性操作的方法
	
	public void stringRedisTemplateDemo(){ //5 set 存储字符串类型
		valOpsStr.set("xx", "yy");
	}
	
	
	public void save(Person person){ //6 set 存储对象类型
		valOps.set(person.getId(),person);
	}
	
	public String getString(){//7 get获得
		return valOpsStr.get("xx");
	}
	
	public Person getPerson(){//8 get获得
		return (Person) valOps.get("1");
	}

}

自定义配置

自动配置的 RedisTemplate ,使用的是 Jdk Serialization Redis Serializer

这对我们演示 Redis Client 很不直观,因为是采用 二进制形式存储数据的

自己配置 Serializer

@SpringBootApplication
public class Ch862Application {

    public static void main(String[] args) {
        SpringApplication.run(Ch862Application.class, args);
    }


    @Bean
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
		template.setConnectionFactory(redisConnectionFactory);

		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setValueSerializer(jackson2JsonRedisSerializer); //1 序列化采用jackson
        template.setKeySerializer(new StringRedisSerializer()); //2 key使用stringRedis

        template.afterPropertiesSet();
		return template;
	}


}

控制器

@RestController
public class DataController {
	
	@Autowired
	PersonDao personDao;
	
	@RequestMapping("/set") //1
	public void set(){
		Person person = new Person("1","wyf", 32);
		personDao.save(person);
		personDao.stringRedisTemplateDemo();
	}
	
	@RequestMapping("/getStr") //2
	public String getStr(){
		return personDao.getString();
	}
	
	@RequestMapping("/getPerson") //3
	public Person getPerson(){
		return personDao.getPerson();
	}
}
http://localhost:8080/set
http://localhost:8080/getStr
http://localhost:8080/getPerson

{
    "id": "1",
    "name": "wyf",
    "age": 32
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章