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
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章